gpt4 book ai didi

ios - 向其发送消息时会保留自身

转载 作者:可可西里 更新时间:2023-11-01 05:34:11 25 4
gpt4 key购买 nike

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 后,实例将被释放。

谁能告诉我系统在这背后所做的工作。谢谢。

最佳答案

-[NSObject performSelectorInBackground:withObject:] 在后台调用 -[NSThread initWithTarget:selector:object:] 确实保留了原始接收器(此处传递为 目标参数)

NSThread 文档:“对象目标和参数在分离线程的执行期间保留。当线程最终退出时它们被释放。”

关于ios - 向其发送消息时会保留自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26459673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com