在这种情况下,我如何泄漏NSString?

时间:2011-06-26 06:26:00

标签: iphone nsstring instruments memory-leaks

我的tableview在最后一行有一个字符串。

@interface MyTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
    NSString *loadingMessage;   
}
@property (retain) NSString *loadingMessage;
@synthesize loadingMessage;

- (UITableViewCell *)tableView:(UITableView *)pTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//some stuff...
        cell.textLabel.text = loadingMessage;
}

然后当某些事件发生时,我将更改加载消息:

-(void)requestFailed:(NSError*)error {
    self.loadingMessage = [NSString stringWithFormat:@"Failed with error: %@", error];
}

根据乐器我在这里泄漏了loadingMessage字符串...但我不明白为什么。我认为stringWithFormat的计数是+0,而setter是+1。当我dealloc时,我释放字符串。我做错了什么?

2 个答案:

答案 0 :(得分:1)

您发布的代码是正确的。实际上,stringWithFormat返回一个自动释放的对象,因此您可以将其直接分配给保留的属性。

因此,您要么在代码中执行其他任务,或者更有可能的是,您未在loadingMessage中发布dealloc

只是一个假设。

答案 1 :(得分:0)

Sergio是对的,代码没有错,但我发现字符串属性需要复制而不是保留。

尝试

@property (copy,readwrite) NSString *loadingMessage;

可能会阻止泄漏

相关问题