【发布时间】:2012-06-05 05:55:55
【问题描述】:
我有一个使用dispatch_once 创建静态对象的类方法。在dispatch_once 块内,我使用[self class],想知道是否需要使用对self 的弱引用来避免保留循环?
+ (NSArray *)accountNames{
static NSArray *names = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
names = [[[self class] accounts] allKeys];
names = [names sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
});
return names;
}
如果我使用对 self 的弱引用,我会收到警告:
+ (NSArray *)accountNames{
static NSArray *names = nil;
static dispatch_once_t predicate;
__weak TUAccount *wself = self;
dispatch_once(&predicate, ^{
names = [[[wself class] accounts] allKeys];
names = [names sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
});
return names;
}
使用“const Class”类型的表达式初始化“TUAccount *__weak”的不兼容指针类型
因为我收到一个警告,所以我认为在这种情况下我不需要使用对 self 的弱引用,但我想看看你们的想法。
【问题讨论】:
标签: objective-c cocoa automatic-ref-counting objective-c-blocks weak-references