繁体   English   中英

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

[英]Why does assigning with a strong property work, but not with a weak one?

我在我的.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。 即self.levelPicker = blah赋值不起作用。

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

@property (strong, nonatomic) UIPickerView *levelPicker;

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

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

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

在这种情况下,您将选择器视图分配给UITextFieldinputView属性。 文本字段将保留选择器视图(我知道这是因为UITextField上的inputView属性是使用修饰符“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;

嗯,简短的回答是,作业确实有效。

但是,由于它是一个弱引用,因此没有保留它,因为没有(其他)强引用您的选择器并且它自动设置为nil。

必须至少有一个强引用任何对象,否则不保留,在这种情况下没有。

有关详细信息,请参阅Apple的“过渡到ARC发行说明”中的“ ARC推出新的终身限定符 ”。

Ray Wenderlich在这里创建了一个很棒的教程。

“强”限定符创建一个所有者关系,用于停止释放对象,这与之前在非ARC世界中所做的相同:

@property(retain) NSObject *obj;

虽然“弱”限定符不会创建所有者关系,因此对象将像以前一样被释放:

@property(assign) NSObject *obj;

在您的情况下,您需要第一个关系,因为您需要实例变量(_levelPicker)来保持新创建的UIPickerView实例。 你做的弱任务实际上有效,但很快就被解除了分配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM