这段代码中的泄漏在哪里,所以我可以打电话给水管工?

sud*_*-rf 0 iphone cocoa-touch memory-management objective-c

好的,抓住了你的头衔.但严肃地说,我无法弄清楚我的代码中泄漏的来源.在仪器中运行它不会显示泄漏,但是当我分析它时它会警告我.这是可疑代码:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *tableIdentifier = @"Table";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableIdentifier];
    }
    NSUInteger row = [indexPath row];

    if (cityCount >= 1) {

        NSString *city = [NSString stringWithFormat:@"%@, %@,  %@", 
                          [[cityData objectAtIndex:row] objectAtIndex:0], 
                          [[cityData objectAtIndex:row] objectAtIndex:1], 
                          [[cityData objectAtIndex:row] objectAtIndex:2]
                          //,[[cityData objectAtIndex:row] objectAtIndex:3]
                          ];

        cell.textLabel.text = city;
        cell.textLabel.font = [UIFont boldSystemFontOfSize:14]; 
        return cell;
    }

    else {
        cell.textLabel.text = @"No cities were found";
        cell.textLabel.font = [UIFont boldSystemFontOfSize:14]; 
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell; //Here's the warning
                     //Potential leak of an object allocated on line 64 and stored into 'cell'
    }
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*rty 10

你需要打电话autorelease.改变这个:

 cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableIdentifier];
Run Code Online (Sandbox Code Playgroud)

对此:

 cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableIdentifier] autorelease];
Run Code Online (Sandbox Code Playgroud)


Jor*_*dão 5

当你分配时cell,你应该autorelease这样做.当您分配某些内容时,您就是所有者,并且必须将其释放.由于您返回单元格,您唯一的选择是自动释放它.

这里查看内存管理规则.

代码应该是这样的:

cell = [[[UITableViewCell alloc] 
  initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableIdentifier]
  autorelease]; 
Run Code Online (Sandbox Code Playgroud)

现在不需要水管工......