kee*_*n3d 7 cocoa weak-references objective-c objective-c-blocks automatic-ref-counting
我有一个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;
}
Run Code Online (Sandbox Code Playgroud)
如果我使用弱引用,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;
}
Run Code Online (Sandbox Code Playgroud)
不兼容的指针类型使用类型为'const Class'的表达式初始化'TUAccount*__ weak'
因为我收到警告,我认为self在这种情况下我不需要使用弱引用,但我想看看你们的想法.
Kur*_*vis 11
这里没有理由担心保留周期,因为保留或释放类对象没有意义 - 保留和释放根本没有效果.
你在做一个弱引用的尝试是错误的,因为你正在服用类对象self,并试图将其转换为实例的TUAccount.这两者是完全不同的东西.
此外,您可以简化:
names = [[[self class] accounts] allKeys];
Run Code Online (Sandbox Code Playgroud)
由于self已经是一个类,[self class] == self,所以这样做:
names = [[self accounts] allKeys];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1322 次 |
| 最近记录: |