如果我有一个名为Catalog的对象,它有一个名为"title“的attrib (非原子的,保留的)attrib。我在目录的dealloc方法中做"attrib发布“:
-(void)dealloc {
[title release], title = nil;
[super dealloc];
}稍后我做"Catalog *c = Catalog new;“。
比较1:
dto.title = [NSString alloc initWithFormat:@“.”,.];
和2:
dto.title = NSString stringWithFormat:@“.”,.;
在dealloc方法中释放对象的所有attrib是常识,但是如果我传递一个访问器方法(它已经有了自动释放),该怎么办?我应该释放还是不释放访问者的属性在dealloc?
发布于 2011-03-30 18:56:22
title的setter保留了字符串,因此需要在-dealloc中释放它。你的第一个案子是错的..。您正在调用+alloc,后面跟着+stringWithFormat:。我怀疑你的意思是-initWithFormat:。另外,您需要在那里释放字符串,因为您正在分配它。在属性上调用-release是丑陋和不可靠的,因此在这种情况下使用临时变量是很常见的:
NSString *string = [[NSString alloc] initWithFormat:...];
dto.title = string;
[string release];发布于 2011-03-30 18:55:10
如果访问器已经有了自动释放,那么就不要在dealloc中再次释放它。new+copy+alloc计数必须与release+autorelease计数匹配。
https://stackoverflow.com/questions/5490771
复制相似问题