0

When not using interface builder I always keep strong references to UI elements:

@interface myViewController : UIViewController 

@property (nonatomic, strong) UILabel *folderLabel;

And then add them like this:

[self.view addSubview self.folderLabel];

where the initialiser is thus:

-(UILabel *)folderLabel{
    if(!_folderLabel) {
        _folderLabel = [[UILabel alloc] init];
        _folderLabel.text = @"foo";
    }
    return _folderLabel
}

I have been told that this is bad for some reason and they should always be weak..

@property (nonatomic, weak) UILabel *folderLabel;

-(UILabel *)folderLabel{
    if(!_folderLabel) {
        UIlabel *folderLabel = [[UILabel alloc] init];
        folderLabel.text = @"foo";
        [self.view addSubview:folderLabel];
        _folderLabel = folderLabel;
    }
    return _folderLabel
}

Is the strong reference a bad thing here?

Lorenzo
  • 3,293
  • 4
  • 29
  • 56
Md1079
  • 1,360
  • 1
  • 10
  • 28
  • Note that the higher voted answer rather than the accepted answer on that question is correct – Paulw11 Oct 07 '15 at 11:35
  • that question refers to IBOulets, this is setting UI Elements programatically – Md1079 Oct 07 '15 at 11:42
  • the highest voted answer appears to be dated with new info about recommendations from apple about keeping them strong.. – Md1079 Oct 07 '15 at 12:14
  • IBOutlet is just syntactic embellishment to allow the NIB binding process to find the property. It doesn't matter how the element is created – Paulw11 Oct 07 '15 at 12:23

1 Answers1

0

When you add the subview to self.view, it gets retained. One pattern that works is to alloc the subview and store it in a local variable, add it to self.view then assign it to the ivar.

user3246173
  • 488
  • 6
  • 18