- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *TelephoneCellId = @"TelephoneCellId";
UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:TelephoneCellId];
UIImageView *imgView;
UILabel *lblName;
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TelephoneCellId] autorelease];
UIView *uiview = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 90.0)];
imgView = [[[UIImageView alloc] initWithFrame:CGRectMake(10.0, 10.0, 60.0, 60.0)] autorelease];
imgView.tag = IMAGE_TAG;
[uiview addSubview:imgView];
lblName = [[[UILabel alloc] initWithFrame:CGRectMake(80.0, 10.0, 200.0, 20.0)] autorelease];
lblName.tag = NAME_TAG;
[uiview addSubview:lblName];
[cell.contentView addSubview:uiview];
[uiview release];
} else {
imgView = (UIImageView *)[cell.contentView viewWithTag:IMAGE_TAG];
lblName = (UILabel *)[cell.contentView viewWithTag:NAME_TAG];
}
NSDictionary *dict = [[[self.telephoneList objectForKey:[self.keys objectAtIndex:[indexPath section]]] objectAtIndex:[indexPath row]] retain];
imgView.image = [UIImage imageNamed:[dict objectForKey:@"image"]];
lblName.text = [dict objectForKey:@"name"];
[dict release];
return cell;
}在上面的代码中,我遇到了一个关于保留和自动释放的问题。如果从que返回的UITableViewCell为零,那么我必须创建一个新的。当我这样做的时候,我会自动释放标签和图像。然后我设置文本/图像。如果UITableViewCell不是nil,那么我可以通过标签找到视图,但是这将返回一个自动释放的对象。我应该保留它吗?然后释放后,我完成了设置的值?或者这是因为视图保留了它,所以它至少是1,因此不释放是安全的?
在这种情况下的帮助是非常感谢的,所以总结一下,什么时候可以在自动释放的对象上继续设置/获取值?
感谢您的宝贵时间:)
发布于 2011-04-02 06:44:26
你想得太多了。
您是否希望此函数获得对象的所有权(并因此承担该对象的责任)?不,当然没有。因此,不要为了这个函数而保留。
您是否希望此代码所在的视图控制器负责某个对象?不:你想把它留在UIKit手中。因此,为了视图控制器的缘故,不要保留。
结论:如果你不想取得所有权,你就不能保留。
此外,不必费心保留(稍后再释放)字典。即使它已经被自动释放到了很快就会消失的地步,这个“很快”也不会在这个函数运行时消失。
发布于 2011-04-02 06:39:31
是的,没有必要保留它。您也不需要保留和释放字典。
https://stackoverflow.com/questions/5519575
复制相似问题