iOS - 通过属性分配ivars

时间:2011-07-21 23:25:02

标签: ios memory-management properties instance-variables

鉴于此实例变量:

UILabel *label;

以下属性:

@property (nonatomic,retain) UILabel *label;

以下综合:

@synthesize label;

以下分配是否正确(关于正确的内存管理):

// 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];
}

1 个答案:

答案 0 :(得分:0)

一切都是正确的。唯一需要注意的是,如果在-viewDidUnload中释放标签,则必须在viewWillLoad中重新创建它。你也是正确的,因为三号不会通过二传手。