TestObj
类是一个简单的类,具有doSomethingInBackground
方法,在其中我将其发送给performSelectorInBackground
方法以使其自身在后台线程中睡眠5秒钟。
@implementation TestObj
- (void)dealloc
{
NSLog(@"%@, is main thread %u", NSStringFromSelector(_cmd), [NSThread isMainThread]) ;
}
- (void)doSomethingInBackground
{
[self performSelectorInBackground:@selector(backgroundWork) withObject:nil] ;
}
- (void)backgroundWork
{
sleep(5) ;
}
@end
我分配并初始化实例,然后将其发送给
doSomethingInBackground
消息,并为其分配nil
以便尽快释放它。TestObj *obj = [[TestObj alloc] init] ;
[obj doSomethingInBackground] ;
obj = nil ;
我发现
dealloc
将在约5秒钟obj = nil;
后运行,似乎系统在将self
方法发送给[self performSelectorInBackground:@selector(backgroundWork) withObject:nil] ;
时保留了backgroundWork
,并且在ojit_code返回之后,实例将被释放。谁能告诉我该系统在此背后所做的工作。谢谢。
最佳答案
后台的-[NSObject performSelectorInBackground:withObject:]
调用-[NSThread initWithTarget:selector:object:]
,它确实保留了原始接收者(此处作为target
参数传递)
NSThread文档:“对象目标和参数在分离线程的执行期间保留。当线程最终退出时,它们将被释放。”