2009-09-22 48 views
1

内的tableView:的cellForRowAtIndexPath:为什么 - [NSObject retainCount]有时会返回意外的值?

// Make a cell: 
UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero  reuseIdentifier:@"Default"] autorelease]; 

// Make a spinner: 
UIActivityIndicatorView *spin = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; 
// [spin retainCount] = 1 

// Start spinning 
[spin startAnimating]; 

[cell.contentView insertSubview:spin atIndex:0]; 
// [spin retainCount] = 3. Huh? 
// I would have expected it to be 2 at this point. 

[spin release]; 
// [[cell.contentView.subviews objectAtIndex:0] retainCount] = 2 

在这一点上,我还以为是cell.contentView.subview上微调一个保留的唯一对象。但显然保留数为2表示其他内容也保留着它。可能有人请向我解释,神秘物体是否在spinner上有一个保留,除了cell.contentView的子视图数组?

干杯,

道格

回答

3

保留您的微调(和其他对象的大量的)被称为NSAutoreleasePool的神秘物体。

在可可中,查看对象retainCount是无用的,因为您无法知道该对象是否曾经(通常是多次)保留自动释放。在通过运行循环的下一次通过之后,retainCount只会在当前池被排空后递减。如果不保留该对象,则会在池被排空时删除该对象。

所以再次,基本的经验法则是:不要看看retainCount

如果有一个autoreleaseCount方法将有可能计算出“逻辑”保留计数,但我怕苹果的工程师离开了这个作为练习开始Cocoa开发;)

+0

实际上,对于对象我米不autoreleasing,retainCount从来没有错过我。我经常和可靠地使用它。我不确定我是否同意你在一般情况下的评估,但在这种特殊情况下,我认为你可能是正确的。 UITableView和UITableViewCell能够掩盖所有欺骗的诡计。 – dugla 2009-09-22 21:12:58

+1

您不必自己自动释放对象,它可以是一些不受您控制的代码。可可和Cocoa-Touch在任何地方都可以使用自动释放的对象。例如,(atomic,retain)属性的合成getter可以做到这一点,以确保getter返回时对象是活着的。还有其他地方,我相信你不知道。 – 2009-09-22 23:14:43

相关问题