gpt4 book ai didi

objective-c - Weak 属性未设置为 nil

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

<分区>

我在 UIViewController 上定义了以下属性:

@property (nonatomic, strong) UIButton *strongButton;
@property (nonatomic, weak) UIButton *weakButton;

这些属性不是通过 Interface Builder 设置的(即,只要我没有在代码中明确设置它们,它们将始终保持为 nil)。

我还在 UIButton 上添加了一个类别以准确知道它何时被释放:

@implementation UIButton (test)
- (void)dealloc { NSLog(@"Dealloc called."); }
@end

我在 UIViewController 的 viewDidLoad 中有以下代码:

self.strongButton = [[UIButton alloc] init];
self.weakButton = self.strongButton;
NSAssert(self.weakButton != nil, @"A: Weak button should not be nil.");
NSLog(@"Setting to nil");
self.strongButton = nil;
NSLog(@"Done setting to nil");
NSAssert(self.weakButton == nil, @"B: Weak button should be nil.");

当我运行该代码时,它在第二个断言 (B) 上失败。日志显示:

  • 设置为零
  • 完成设置为零
  • * -[ViewController viewDidLoad] 断言失败
  • * 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“B:弱按钮应为零。”

但是,当我注释掉第一个断言时:

self.strongButton = [[UIButton alloc] init];
self.weakButton = self.strongButton;
//NSAssert(self.weakButton != nil, @"A: Weak button should not be nil.");
NSLog(@"Setting to nil");
self.strongButton = nil;
NSLog(@"Done setting to nil");
NSAssert(self.weakButton == nil, @"B: Weak button should be nil.");

代码在日志中运行良好:

  • 设置为零
  • 调用 Dealloc。
  • 完成设置为零

请注意在第一个场景中 dealloc 没有在正确的时间被调用。

为什么第一个 NSAssert 会导致这种奇怪的行为?这是错误还是我做错了什么?

(我在 iOS 6.1 上)

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