NSString:为属性赋值时发生泄漏

时间:2016-05-25 13:01:09

标签: ios objective-c memory-leaks properties nsstring

假设我们不使用ARC。 假设我们有一个非常简单的类,我们在其中声明2个NSString属性,如下所示:

@implementation Foo
@synthesize message, title;

-(id)initWithArguments:(NSString*)mess title:(NSString*)tit{
if((self = [super init])){
message = mess; // (1)
self.title = tit; // (2)
(...)
}
return self;
}

-(void)dealloc{
message = nil;
title = nil;
[super dealloc];
}
@end

并在实施中:

-(void)someMethod{
NSString *string1 = [NSString stringWithFormat:@"some text with %d things", 5];
NSString *string2 = [NSString stringWithFormat:@"other text with %d things", 5];

Foo *foo = [[Foo alloc] initWithArguments:string1 title:string2];
}

现在,如果我从另一个类调用一个方法,我在其中创建2个NSString和一个Foo实例,如下所示:

RadioDevice

整个代码运行良好且不会崩溃,但是,如果我用仪器对其进行分析,

  • 调用(1)时不会导致泄漏(" message = mess;")
  • 调用时会导致泄漏(2)(" self.title = tit;")

这非常令人困惑,因为stringWithFormat是一个自动释放的对象,不是吗? 那么,在分配属性时,自动释放的对象如何导致泄漏???

我在某处读到,使用" self.text = value几乎总是更好;"形式而不是" text = value;"形式,因为第二个可能导致泄漏。

实际上,在这段代码中恰恰相反。

并且...如果我使用像@"一些文本"这样的常量NSString,而不是[NSString stringWithFormat]返回的值,当然没有泄漏。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

在以下几种情况下,您忘记调用(编译器生成的)setter方法:

self.message = mess;    // in init method

self.message = nil;     // in dealloc method
self.title = nil;       // ditto

在非ARC代码中使用setter / getter方法至关重要。

相关问题