【发布时间】:2012-12-04 08:16:43
【问题描述】:
我有一个non-gc OS X 应用程序。在这个应用程序中,我试图从块内将一个对象分配给一个块变量。然后这个对象被另一个线程从它所在的数组中清除。我假设因为它是一个non-gc 应用程序,所以block_byref 结构正在设置BLOCK_NEEDS_FREE 标志,并且dispose 辅助函数正在清理对象。副本是否足够安全?
- (void)assignFromArray
{
__block NSObject iWantToKeep = nil;
[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
if([[obj stringVar] isEqualToString:MyStringConst])
{
iWantToKeep = [obj copy];
*stop = YES;
}
}];
/* Assume here that the array has been cleaned up by another thread
* and all the objects in it have been released.
*
* Was a copy safe enough to survive the block_byref dispose
* and the array objects being dealloc'd so that it can be accessed here?
*/
NSLog(@"%@", [iWantToKeep stringVar]);
//I only need it briefly, so it can be cleaned up here
[iWantToKeep autorelease];
}
【问题讨论】:
-
您可以在您的区块中注销 iWantToKeep 值吗?
-
是的,但实际的方法不是 NSLog。 NSLog 实际上被一个相当长的传递对象指针的方法所取代,所以它需要发生在块之外。
-
你不能有
NSObject类型的变量
标签: objective-c macos cocoa memory-management objective-c-blocks