加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 为什么分配一个强大的属性工作,而不是弱工作?

发布时间:2020-12-16 10:21:32 所属栏目:百科 来源:网络整理
导读:我在我的.h文件中声明了一个属性 @property (weak,nonatomic) UIPickerView *levelPicker; 在我的实现文件中合成为: @synthesize levelPicker = _levelPicker; 然后我在同一个实现文件中有一个代码块,它执行以下操作: if (self.levelPicker == nil) { self
我在我的.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所说,你的对象需要至少一个强(保留)引用,否则它们将不会被保留.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读