ios – 发送消息时自我保留

ios – 发送消息时自我保留,第1张

概述TestObj类是一个简单的类,它有一个方法doSomethingInBackground,我在其中发送performSelectorInBackground方法,使自己在后台线程中休眠5秒. @implementation TestObj- (void)dealloc{ NSLog(@"%@, is main thread %u", NSStringFromSelector(_cm 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文档:“在分离线程执行期间保留对象target和argument.它们在线程最终退出时释放.”

总结

以上是内存溢出为你收集整理的ios – 发送消息时自我保留全部内容,希望文章能够帮你解决ios – 发送消息时自我保留所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1060801.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-25
下一篇2022-05-25

发表评论

登录后才能评论

评论列表(0条)

    保存