我希望能够在新线程上调用对象的方法;但是,我对如何管理保留计数感到困惑(或者即使这是一个问题)。
在非线程场景中,我会这样做:
MyObject *newObject = [[MyObject alloc] init];
[newObject doSomething];
[newObject release];
在这种情况下,一切都很好。但是,我的问题是以下线程版本是否有问题:
MyObject *newObject = [[MyObject alloc] init];
[NSThread detachNewThreadSelector:@selector(doSomething)
toTarget:newObject
withObject:nil];
[newObject release];
在这种情况下,我是否需要担心 -doSomething
正在处理时 newObject
被释放?如果答案是肯定的,那么让 -doSomething
保留 self
似乎很麻烦。
这是一个问题吗?如果是这样,正确的解决方案是什么?
最佳答案
来自 Xcode API 文档:
The objects aTarget and anArgument are retained during the execution of the detached thread, then released. The detached thread is exited (using the exit class method) as soon as aTarget has completed executing the aSelector method.
所以,您的编码方式很好。您可以而且应该发布 newObject。
关于objective-c - NSThread 和对象保留计数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/563365/