4

When I create a variable I want to assign to a property I can do the following (assuming the property is @property (nonatomic,retain) UILabel *myLabel;):

UILabel *temp = [[UILabel alloc] init];
self.myLabel = temp;
[temp release];

What would happen in the following scenario where temp is not used?

self.myLabel = [[UILabel alloc] init];
[myLabel release];

This is assuming I would add a [myLabel release]; in dealloc due to the property.

Would this be proper memory management? In the second example does myLabel have a retain count of 2 after the init line?

jmosesman
  • 716
  • 1
  • 11
  • 24

2 Answers2

5

The second might happen to work, but is incorrect. The first line calls setMyLabel:. That may happen to set an ivar, it may not. It might do all kinds of things (it might make a copy, it might store the information elsewhere, etc). Your second line releases an ivar. If the setter happens to be implemented the way you're assuming, then you will get lucky and it will work. But this is not correct memory management.

The first example is correct. You can also use the autorelease pool to simplify things. Better is to move your code to ARC, which solves all of these problems faster and more easily.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
-1

Assigning to a retain property will automatically call retain on the object assigned to (and call release on the previous object). So yes, after

self.myLabel = [[UILabel alloc] init];

[myLabel retainCount] will return 2, one from init and one from assigning the property. So you should either add autorelease to the line above, or call release before the function exits.

Hampus Nilsson
  • 6,692
  • 1
  • 25
  • 29