iOS : 块中的实例变量
iOS : instance variable in block
我的对象有一些实例变量,像这样:
@interface MyObject : NSObject
{
@private
NSDictionary * resultDictionary ;
}
这是方法:
- (void) doSomething
{
__weak typeof(self) weakSelf = self ;
[TaskAction invoke:^(NSDictionary* result){
if(result){
weakSelf->resultDictionary = result ; // dereferencing a weak pointer is not allowed due to possible null value caused by race condition , assign it to strong variable first ...
}
}]
}
iOS 编译器抛出错误:// 不允许取消引用弱指针,因为竞争条件可能导致 null 值,首先将其分配给强变量 ...
错误语句是:weakSelf->resultDictionary = result ;
你能帮我看看为什么会出错吗。
您实际上不需要此代码中的弱引用。这里没有保留循环的风险。
但是,如果您这样做,解决方案是为私有 ivar 创建一个 属性。然后你可以通过块内的弱指针访问属性。
旁注 - 不要将私有变量放在 public 界面中。没有充分的理由将私人详细信息放在 public 界面中。将私有ivar(或私有属性)放在.m文件的私有class扩展名中。
.h 文件:
@interface MyObject : NSObject
@end
.m 文件:
@interface MyObject()
@property (nonatomic, strong) NSDictionary *resultDictionary;
@end
@implementation MyObject
- (void)doSomething {
[TaskAction invoke:^(NSDictionary* result){
if (result){
self.resultDictionary = result;
}
}];
}
@end
我的对象有一些实例变量,像这样:
@interface MyObject : NSObject
{
@private
NSDictionary * resultDictionary ;
}
这是方法:
- (void) doSomething
{
__weak typeof(self) weakSelf = self ;
[TaskAction invoke:^(NSDictionary* result){
if(result){
weakSelf->resultDictionary = result ; // dereferencing a weak pointer is not allowed due to possible null value caused by race condition , assign it to strong variable first ...
}
}]
}
iOS 编译器抛出错误:// 不允许取消引用弱指针,因为竞争条件可能导致 null 值,首先将其分配给强变量 ...
错误语句是:weakSelf->resultDictionary = result ;
你能帮我看看为什么会出错吗。
您实际上不需要此代码中的弱引用。这里没有保留循环的风险。
但是,如果您这样做,解决方案是为私有 ivar 创建一个 属性。然后你可以通过块内的弱指针访问属性。
旁注 - 不要将私有变量放在 public 界面中。没有充分的理由将私人详细信息放在 public 界面中。将私有ivar(或私有属性)放在.m文件的私有class扩展名中。
.h 文件:
@interface MyObject : NSObject
@end
.m 文件:
@interface MyObject()
@property (nonatomic, strong) NSDictionary *resultDictionary;
@end
@implementation MyObject
- (void)doSomething {
[TaskAction invoke:^(NSDictionary* result){
if (result){
self.resultDictionary = result;
}
}];
}
@end