I have a property declared in my .h file as
@property (weak, nonatomic) UIPickerView *levelPicker;
which is synthezised in my implementation file as:
@synthesize levelPicker = _levelPicker;
I then have a code block in the same implementation file which does the following:
if (self.levelPicker == nil) {
self.levelPicker = [[UIPickerView alloc] initWithFrame:CGRectZero];
self.levelPicker.delegate = self;
self.levelPicker.dataSource = self;
}
textField.inputView = self.levelPicker;
In this case, self._levelPicker is not set to the new UIPickerView. I.e. the self.levelPicker = blah assignment doesn’t work.
However, if I change the property declaration to:
@property (strong, nonatomic) UIPickerView *levelPicker;
then everything works as expected and _levelPicker is set to the newly allocated UIPickerView.
Can someone please tell me why this is the case? I thought I was coming to an understanding of how references work, but I guess I still have more to learn. I read some of the other related SO posts, but it’s still not entirely clear to me.
As @Inazfiger says, your objects need at least one strong (retaining) reference, otherwise they won’t be retained.
In this case, you’re assigning the picker view to a
UITextField‘sinputViewproperty. The text field will retain the picker view (I know this because theinputViewproperty onUITextFieldis declared with the modifiers “readwrite, retain“), but only once you’ve made the assignment. So if you want to stick with a weak reference, you need to rearrange your code slightly – something like this: