为什么要分配一个强大的财产工作,而不是弱工作?

Ben*_*int 3 weak-references objective-c ios automatic-ref-counting

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

@property (weak, nonatomic) UIPickerView *levelPicker;
Run Code Online (Sandbox Code Playgroud)

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

@synthesize levelPicker = _levelPicker;
Run Code Online (Sandbox Code Playgroud)

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

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

在这种情况下,self._levelPicker未设置为新的UIPickerView.即self.levelPicker = blah赋值不起作用.

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

@property (strong, nonatomic) UIPickerView *levelPicker;
Run Code Online (Sandbox Code Playgroud)

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

有人可以告诉我为什么会这样吗?我以为我正在理解参考是如何工作的,但我想我还有更多要学习的东西.我读了一些其他相关的SO帖子,但对我来说仍然不完全清楚.

Sim*_*ker 7

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

在这种情况下,您将选择器视图分配给UITextFieldinputView属性.文本字段将保留选择器视图(我知道这是因为inputView属性on UITextField使用修饰符"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;
Run Code Online (Sandbox Code Playgroud)