【问题标题】:Can't figure out why this is a memory leak, please advice!不知道为什么这是内存泄漏,请指教!
【发布时间】:2010-08-10 21:14:10
【问题描述】:

我有这个 UITableView 应用程序,一个基本的日记应用程序,在这个方法中 XCode 说我有内存泄漏。建议开始泄漏的第一行是 117 "NSString *CellIdentifier"。 到 if (cell ==..., 到 Diary *diaryEntry, 到 NSString *stringDate. 它声明该方法返回一个拥有 +1 保留计数的对象。 我试图释放单元格,stringDate...没有什么能改变这个事实,那么我在想什么/做错了什么?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

// A date formatter for the time stamp static 

static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}

Diary *diaryEntry = [diaryArray objectAtIndex:indexPath.row];

cell.textLabel.text = diaryEntry.diaryTitle;

NSString *stringDate = [[DiaryDateFormatter alloc] convertDateToString:[diaryEntry diaryDate]];

cell.detailTextLabel.text = stringDate;    

[stringDate release];
return cell;

}

【问题讨论】:

    标签: objective-c iphone


    【解决方案1】:

    这行看起来有问题:

    NSString *stringDate = [[DiaryDateFormatter alloc] convertDateToString:[diaryEntry diaryDate]];
    
    1. 一旦分配了一个类的实例,就需要对其进行初始化。如果convertDateToString: 是一个初始化方法,那么它应该被重命名。但是,看起来convertDateToString: 无论如何都应该是一个类方法(这样您就不必分配DiaryDateFormatter 类的实例)。
    2. alloc 方法始终为您提供一个保留计数为 +1 的对象。因此,您有责任释放它。您的代码设置方式意味着您不能再访问分配的对象以释放它。

    试着把上面这行代码改成这样:

    DiaryDateFormatter *formatter = [[DiaryDateFormatter alloc] init];
    NSString *stringDate = [formatter convertDateToString:[diaryEntry diaryDate]];
    [formatter release];
    

    另外,不要释放stringDate,因为它不是使用名称暗示您拥有所有权的方法获得的。

    【讨论】:

    • 我终于想通了,感觉就像年龄一样。但是现在我已经杀死了那个隐蔽的DateToSting 东西。只是引起了问题。问题解决后。
    【解决方案2】:

    我看到了问题。你正在使用objective-c,但你并不擅长它(像我一样!)

    更重要的是,IIRC 如果要返回单元格,您应该使用 autorelease 而不是 alloc 单元格?这就是我跳船前的全部记忆……

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-04
      • 2016-08-03
      • 2013-03-23
      • 2012-01-01
      • 2013-10-16
      相关资源
      最近更新 更多