objective-c - 为什么赋值给强属性有效,但给弱属性赋值却不行?

标签 objective-c ios automatic-ref-counting weak-references

我在 .h 文件中声明了一个属性

@property (weak, nonatomic) UIPickerView *levelPicker;

在我的实现文件中合成为:

@synthesize levelPicker = _levelPicker;

然后我在同一个实现文件中有一个代码块,它执行以下操作:

if (self.levelPicker == nil) {
    self.levelPicker = [[UIPickerView alloc] initWithFrame:CGRectZero];
    self.levelPicker.delegate = self;
    self.levelPicker.dataSource = self;
}
textField.inputView = self.levelPicker;

在这种情况下,self._levelPicker 没有设置为新的 UIPickerView。 IE。 self.levelPicker = blah 分配不起作用。

但是,如果我将属性声明更改为:

@property (strong, nonatomic) UIPickerView *levelPicker;

然后一切都按预期工作,_levelPicker 设置为新分配的 UIPickerView。

谁能告诉我为什么会这样?我以为我对引用的工作原理有了一定的了解,但我想我还有很多东西要学。我阅读了一些其他相关的 SO 帖子,但我仍然不完全清楚。

最佳答案

正如@Inazfiger 所说,您的对象至少需要一个强(保留)引用,否则它们将不会被保留。

在这种情况下,您将选择器 View 分配给 UITextFieldinputView 属性。文本字段将保留选择器 View (我知道这一点是因为 UITextField 上的 inputView 属性是 declared with the modifiers "readwrite, retain" ),但是只有在您完成分配后。所以如果你想坚持弱引用,你需要稍微重新安排你的代码 - 像这样:

// Declare a temporary UIPickerView reference. By default, this is
// a strong reference - so tempPicker will be retained until this
// variable goes out of scope.
UIPickerView *tempPicker = [[UIPickerView alloc] initWithFrame:frame];

// Configure the picker
tempPicker.delegate = self;
tempPicker.dataSource = self;

// Assign the picker view to the text field's inputView property. This
// will increase the picker's retain count. Now it'll no longer be
// released when tempPicker goes out of scope.
textField.inputView = tempPicker;

// Finally, assign the same object to self.levelPicker - it won't
// go out of scope as long as it remains assigned to textField's
// inputView property, and textField itself remains retained.
self.levelPicker = tempPicker;

关于objective-c - 为什么赋值给强属性有效,但给弱属性赋值却不行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9649177/

相关文章:

ios - 内存未在 ios View 层次结构中释放

ios - 在没有调用 viewDidUnload 的情况下在 popViewControllerAnimated 之后调用 Dealloc

ios - S3GetObjectMetadataResponse 错误,崩溃。我怎样才能检查它?

ios - clang : error: linker command failed with exit code 1 (use -v to see invocation) in iOS app after deleting AdMob

objective-c - OS X 10.10.3 和通知中心

iOS 控制音量

ios - 即使使用 Delegate=self 也不会调用 WebView 委托(delegate)并且还实现了 UIWebView 委托(delegate)协议(protocol)

ios - 当使用 ARC 从 UIView 调用 dealloc 时,我可以假设 ivars 仍然保留吗?

ios - NSDateFormatter dateFormatFromTemplate 问题

iphone - Xcode:调试意外的 iOS 应用程序崩溃