【问题标题】:How to return new allocated object in function on Objective-C?如何在Objective-C的函数中返回新分配的对象?
【发布时间】:2013-04-06 19:14:14
【问题描述】:

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

- (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 内存管理指南中给出的命名约定规则

【问题讨论】:

    标签: objective-c memory-management


    【解决方案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;
    }
    

    【讨论】:

    • 当然这是假设您没有使用 ARC。在 ARC 下,您只需返回单元格,ARC 就会隐含地做正确的事情。
    【解决方案2】:

    对于 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+ 下,你只需要像这样为表格视图注册你想要的 Cell:

    [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;
    }
    

    【讨论】:

      猜你喜欢
      • 2010-12-13
      • 1970-01-01
      • 1970-01-01
      • 2015-09-11
      • 2017-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多