为什么 - [NSObject retainCount]有时会返回意外值?

时间:2009-09-22 19:31:52

标签: iphone cocoa-touch uitableview

在tableView中:cellForRowAtIndexPath:

// 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是唯一一个在微调器上有一个retain的对象。但显然保留计数为2表示其他东西也保留了它。有人可以向我解释除了cell.contentView的子视图数组之外,哪个神秘对象在spinner上有一个保留?

干杯,

道格

1 个答案:

答案 0 :(得分:3)

保留你的微调器(和许多其他物体)的神秘物体称为NSAutoreleasePool

在Cocoa中,查看对象retainCount是没用的,因为您无法知道对象之前是否已被保留 - 自动释放(通常很多次)。 retainCount仅在当前池耗尽后才会减少,通常是在下一次运行循环之后。如果您不保留该对象,则在池耗尽时将删除该对象。

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

如果有autoreleaseCount方法可以计算“逻辑”保留计数,但我担心Apple的工程师将此作为开始Cocoa开发人员的练习;)