// ClassA.m
NSString *strA = [[NSstring alloc] initWithString:@"test string"];
ClassB *classB = [[ClassB alloc] init];
[classB setStrB:strA];
[strA release];
// classB will be released later
// ClassB.h
@property (nonatomic, retain) NSString *strB;
// ClassB.m
// custom setter
-(void) setStrB:(NSString *)newStr {
strB = newStr;
}
strB会泄露吗?是否应该在ClassB dealloc方法中释放?
最佳答案
我假设你还没有合成属性,你定义的自定义 setter 就是所有被调用的...如果是这样,那么你实际上过度释放了你的字符串,因为你没有保留你的属性
NSString *strA = [[NSstring alloc] initWithString:@"test string"]; //string with +1 ref
ClassB *classB = [[ClassB alloc] init];
[classB setStrB:strA]; //doesnt increase the ref count
[strA release]; //string with 0 ref count (which means OS will reclaim the memory allocated for the string)
现在,如果您尝试访问 classB strB 属性,您可能会因过度释放而崩溃
-(void)setStrb:(NSString*)a
{
if(a==nil)
strB=nil;
else
{
[a retain];
if(strB)
[strB release];
strB=a;
}
}
如果您要在 setter 中保留字符串,那么是的,您应该在 classB dealloc 中释放它。但实际上您必须小心编写 setter 的方式(您可能应该只是合成并让属性为您生成),这是 setter 的实际外观
在这里你释放 strB 如果它不是 nil 在你实际设置它之前,它会检查 a 是否为 nil 在这种情况下你只需将 strB 设置为 nil,否则你将 strB 设置为 a 并保留
希望对你有帮助
关于ios - 内存管理 : does this code has a memory leak?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4044073/