2013-04-06 81 views
0

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

- (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) 
} 

对象泄露:分配并存储到“细胞”的对象是从它的名称的方法返回(“:的cellForRowAtIndexPath:的tableView”)不与“复制”,“mutableCopy”,“的alloc”或'新'。这违反了内存管理指南中的可可

的命名约定规则

回答

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; 
} 
+1

当然这是假设你不使用ARC。在ARC下,您只需返回该单元格,ARC就会隐含地执行正确的操作。 – 2013-04-06 19:40:09

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