gpt4 book ai didi

objective-c - 属性(property)不保留 (ARC)

转载 作者:搜寻专家 更新时间:2023-10-30 19:46:29 25 4
gpt4 key购买 nike

我有一个以表单样式显示的模态视图 Controller 。它有一个委托(delegate)协议(protocol)。我正在实现该协议(protocol)并在演示之前分配一个委托(delegate),但即使属性很强大,它也会丢失。欢迎任何可能的原因。谢谢!

这里是属性声明,as strong。

@protocol SDStoreViewDelegate <NSObject>
// Methods
@end

@interface SDStoreViewController : UIViewController

@property (strong, nonatomic) id <SDStoreViewDelegate> delegate;

@end

这是创建对象和设置委托(delegate)的地方。

SDStoreViewController *store = [[SDStoreViewController alloc] init];
[store setDelegate:self];

NSLog(@"1 %@",store.delegate); // Returns Object as expected

[self presentViewController:store animated:YES completion:^{
NSLog(@"3 %@",store.delegate); // Returns Object as expected
}];

NSLog(@"4 %@",store.delegate); // Returns Object as expected

这是SDStoreViewController的viewDidLoad。它已经失去了它的委托(delegate)

- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"3 %@",_delegate); // Returns NULL
}

这是解雇,只是因为在调用委托(delegate)的地方它不是 NULL。

- (void)dismiss:(id)sender
{
NSLog(@"5 %@",_delegate); // Returns NULL

[self.delegate aMethod];
}

更新

我同时使用了weakstrong 引用。我还使用了 self.delegate_delegate 来访问该属性。作为一个要点,aMethod 回调没有通过,这促使这项侦探工作找到它迷路的地方。

最佳答案

首先,delegate 属性必须始终 weakunsafe_unretained 否则ARC 无法释放具有相互强指针的类。

@property (weak, nonatomic) id <SDStoreViewDelegate> delegate;

@property (unsafe_unretained, nonatomic) id <SDStoreViewDelegate> delegate;

您为什么不尝试通过 getter 访问 delegate 属性?像这样:

NSLog(@"4 %@",self.delegate);

代替

NSLog(@"4 %@",_delegate);

还有一个额外的问题:你的方法在那一行被回调了吗?

[self.delegate aMethod];

如果答案是肯定的,你还没有丢失你的delegate,如果答案是否定的,你在哪里设置你的delegate

关于objective-c - 属性(property)不保留 (ARC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12148113/

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