1

I created a property

 @property (weak,nonatomic) UILabel *vishalSays;

Then I am trying to initialize the property like below:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.vishalSays = [[UILabel alloc] initWithFrame:CGRectMake(30, 100, 200, 44)];
    [self.vishalSays setText:@"Hello World"];
    [self.view addSubview:self.vishalSays];
}

But the above code does not display label in the iPhone simulator. When changing the code to below:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, 100, 200, 44)];
    self.vishalSays = label;
    [self.vishalSays setText:@"Hello World"];
    [self.view addSubview:self.vishalSays];
}

then the "Hello World" label becomes visible. Can someone explain why is there a behavior difference between the two syntax? Thanks Vishal

1 Answers1

0

I think it's because your property is set to weak. You can either change it to strong (preferred), or add a retain block around the initialisation (not sure if this will work, and not at the computer to test it).

If you're using ARC, then the initialisation will not be retained because nothing owns the instance.

For more, see: https://stackoverflow.com/a/11013715/785791

Community
  • 1
  • 1
TeaPow
  • 687
  • 8
  • 17