0

如何在函数中返回新分配的对象?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"liteCell"];
    [cell.textLabel setText:@"Lite"];
    return cell; // Object returned to caller as an owning reference (single retain count transferred to caller)
}

对象泄露:分配并存储到“cell”中的对象是从名称(“tableView:cellForRowAtIndexPath:”)不以“copy”、“mutableCopy”、“alloc”或“new”开头的方法返回的。这违反了 Cocoa 内存管理指南中给出的命名约定规则

4

2 回答 2

1

在这种情况下,您应该返回一个自动释放的对象,因此解决方案是

UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault] autorelease]; 

哦,更好的方法是也使用[tableView dequeueReusableCellWithIdentifier:CellIdentifier],像这样:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (nil == cell) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }

    return cell;
}
于 2013-04-06T19:27:20.483 回答
0

对于 iOS 5,您需要检查单元格是否已经实例化,如果没有,您需要实例化单元格:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (nil == cell) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }

    return cell;
}

在 iOS 6+ 下,您只需要为表格视图注册所需的单元格,如下所示:

[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIdentifier];

然后稍后您可以使用:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

并且总是会收到一个分配的单元格,所以你可以写

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    return cell;
}
于 2014-02-07T11:06:25.957 回答