开发者

NSThread running a class

开发者 https://www.devze.com 2022-12-29 06:00 出处:网络
Every the example I find on the internet (including Apple doc) sets the target to self like this : [NSThread detachNewThreadSelector:@selector(threadedTask) toTarget:self 开发者_运维百科withObject:ni

Every the example I find on the internet (including Apple doc) sets the target to self like this :

[NSThread detachNewThreadSelector:@selector(threadedTask) toTarget:self 开发者_运维百科withObject:nil];

Since i would like to do a more complex task in background (involving multiple methods), I thought of creating a class Task called like this :

Task *task = [[Task alloc] init];
[NSThread detachNewThreadSelector:@selector(main) toTarget:task withObject:nil];

but I wonder, how will be handled the instance variables of my class Task ? in my method main can I safely call methods of my class Task using [self myMethod] and modifying members variables assuming I'm the only thread accessing it ?

This way of handling threads seems weird to me, sorry if my question is stupid ^^

Thanks in advance


If there's only one NSThread (including the main thread) for each Task then yes, you can do whatever you want. As soon as more than one thread can be accessing certain data simultaniously, you'll have to provide synchronization.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号