gpt4 book ai didi

iOS : instance variable in block

转载 作者:行者123 更新时间:2023-11-28 19:43:57 25 4
gpt4 key购买 nike

我的对象有一些实例变量,像这样:

@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;

你能帮我看看为什么会出错吗。

最佳答案

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

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

旁注 - 不要将私有(private) ivar 放在公共(public)界面中。没有充分的理由将私有(private)细节放在公共(public)界面中。将私有(private) ivar(或私有(private)属性)放在 .m 文件的私有(private)类扩展中。

.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

关于iOS : instance variable in block,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33227683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com