C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了objective-c – 为什么分配一个强大的属性工作,而不是弱工作?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我在我的.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帖子,但对我来说仍然不完全清楚.

解决方法

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

在这种情况下,您将选择器视图分配给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];

// Con@L_944_11@ure 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 – 为什么分配一个强大的属性工作,而不是弱工作?全部内容,希望文章能够帮你解决objective-c – 为什么分配一个强大的属性工作,而不是弱工作?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。