简体   繁体   中英

iOS - assignment of ivars through properties

Given this instance variable:

UILabel *label;

And the below property:

@property (nonatomic,retain) UILabel *label;

And the following synthesize:

@synthesize label;

Are these below assignments correct (with respect to correct memory management):

// 1
UILabel *tmpLabel = [[UILabel alloc] initWithFrame:CGSizeZero];
self.label = tmpLabel;
[tmpLabel release];

// 2
self.label = [[[UILabel alloc] initWithFrame:CGSizeZero] autorelease];

// 3 - This one looks shady but I haven't gotten any leaks ( I suppose this will
// not use the created setter)
label = [[UILabel alloc] initWithFrame:CGSizeZero];

- (void)viewDidUnload {
    self.label = nil;
    [super viewDidUnload];
}

- (void)dealloc {
    [label release];
    [super dealloc];
}

All are correct. The only thing to note is that if you release label in -viewDidUnload you will have to recreate it in viewWillLoad. You are also correct in that number three will not go through the setter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM