iOS:块中的实例变量

iOS:块中的实例变量,ios,pointers,block,lifecycle,weak,Ios,Pointers,Block,Lifecycle,Weak,我的对象有一些实例变量,如下所示: @interface MyObject : NSObject { @private NSDictionary * resultDictionary ; } 方法如下: - (void) doSomething { __weak typeof(self) weakSelf = self ; [TaskAction invoke:^(NSDictionary* result){ if(result){

我的对象有一些实例变量,如下所示:

@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编译器抛出错误://由于竞争条件可能导致空值,不允许取消引用弱指针,请先将其分配给强变量

错误语句是:weakSelf->resultDictionary=result


你能帮我解释一下错误的原因吗。

在这段代码中,你实际上不需要弱引用。这里没有保留周期的风险

但是,如果您这样做了,解决方案将是为私有ivar创建一个属性。然后可以通过块内的弱指针访问属性

旁注-不要将私有IVAR放在公共接口中。没有充分的理由将私有详细信息放在公共接口中。将私有ivar(或私有属性)放在.m文件的私有类扩展名中

.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

在我看来,你错了。1、 如果创建属性,ivar的状态将不是私有的。2、 在块中,我们不能使用self,“self”指针是强指针no,属性是私有的。它在私有类扩展中定义。在这种情况下,强烈地引用self并没有什么错。没有参考循环。试试看,他们不必使用属性——如果他们愿意,他们可以使用ivar;尽管我同意ivar应该在扩展或实现中声明,而不是在接口中声明。@newacct是的,您可以使用“strong”
self
访问ivar。但您不能通过“弱”的
自我访问ivar。由于最初使用了“弱”
self
,所以我建议使用该属性。然后我意识到代码根本不需要弱指针。