使用以下代码:
@interface MyClass()
{
NSMutableArray * dataArray;
}
@end
@implementation MyClass
- (void) doSomething
{
__typeof__(self) __weak wself = self;
dispatch_async(dispatch_get_global_queue(0,0), ^{
__typeof__(self) sself = wself;
[sself->dataArray addObject: @"Hello World"];
dispatch_async(dispatch_get_main_queue(), ^{
[NSThread sleepForTimeInterval: 30];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: sself->dataArray[0]
message: @"Message"
delegate: nil
cancelButtonTitle: @"OK"
otherButtonTitles: nil];
[alert show];
});
});
}
@end
- 这样从主队列块中访问
sself
是否正确? - 一旦初始队列完成,
sself
会失效吗? - 我应该在主队列块内再添加第二个
__typeof__(self) sself = wself;
吗?
weakSelf
/strongSelf
模式。您真正需要做的是在存在潜在强引用循环的情况下。但与您其他的问题不同,这里没有潜在的强引用循环。如果您真的担心对象在代码执行sleepForTimeInterval
的时候被保留,那么您可以使用weakSelf
/strongSelf
进行操作,但值得注意的是在这种情况下你不必要这样做。 - Rob