保留合成属性的计数
请查看我的代码:
@interface ClassA : NSObject {
ClassB *objB;
}
@property (retain) ClassB *objB;
@end
@implementation ClassA:
@synthesiaze objB;
@end
int Main(int argc, const char *argv[])
{
ClassA *objA = [[ClassA alloc] init];
ClassB *objB = [[ClassB alloc] init];
NSLog(@"%d", (int)[objB retainCount]); // 1
NSLog(@"%d", (int)[[objA objB] retainCount]); // 0
objA.objB = objB;
NSLog(@"%d", (int)[objB retainCount]); // 2
/* --> */ NSLog(@"%d", (int)[[objA objB] retainCount]); // 3
NSLog(@"%d", (int)[[objA objB] retainCount]); // 4
NSLog(@"%d", (int)[objB retainCount]); // 4
}
请查看第 23 行, NSLog(@"%d", (int)[[objA objB] keepCount]);
我认为结果应该是 2 而不是 3,但是每个一次,调用 [objA objB]
似乎将保留计数增加了 1。我不知道发生了什么。谁能告诉我?谢谢!
Please review my code:
@interface ClassA : NSObject {
ClassB *objB;
}
@property (retain) ClassB *objB;
@end
@implementation ClassA:
@synthesiaze objB;
@end
int Main(int argc, const char *argv[])
{
ClassA *objA = [[ClassA alloc] init];
ClassB *objB = [[ClassB alloc] init];
NSLog(@"%d", (int)[objB retainCount]); // 1
NSLog(@"%d", (int)[[objA objB] retainCount]); // 0
objA.objB = objB;
NSLog(@"%d", (int)[objB retainCount]); // 2
/* --> */ NSLog(@"%d", (int)[[objA objB] retainCount]); // 3
NSLog(@"%d", (int)[[objA objB] retainCount]); // 4
NSLog(@"%d", (int)[objB retainCount]); // 4
}
Please look at line 23, NSLog(@"%d", (int)[[objA objB] retainCount]);
I think the result should be 2 not 3, but every time, calling [objA objB]
seems to increase the retain count by 1. I don't know what's happening. Who can tell me? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
苹果有这样的说法:
retainCount
:不用担心保留计数;如果您调用
retain
、alloc
或名称以copy
、< 开头的方法,只需担心调用release
即可。代码>mutableCopy,或new
。Apple has this to say about
retainCount
:Don't worry about retain counts; just worry about calling
release
if you callretain
,alloc
, or a method whose name starts withcopy
,mutableCopy
, ornew
.首先,不要依赖
retainCount
始终保持 100% 准确。也就是说,您所看到的只是因为合成的 getter 看起来像这样:
因此,当您通过合成的 getter 请求对象时,它会被保留并自动释放。这是因为从非所有权 getter 获得的任何内容都应该在当前自动释放池的生命周期内持续存在,但如果您在此期间释放了 objA,那么情况就不会如此。
First of all, don't rely on
retainCount
to always be 100% accurate.That said, what you're seeing is just because the synthesised getter looks like this:
So, when you ask for the object through a synthesised getter, it is retained and autoreleased. That's because anything you get from a non-ownership getter is supposed to last for the life of the current autorelease pool, but if you released objA in the interim then that wouldn't be the case.
你的@property没有被标记为非原子,所以getter不仅仅是一个简单的返回,而是一个锁、保留、自动释放和解锁——出于线程安全的目的。您可以编写自己的 getter 或将属性声明为 @property(非原子,保留)
Your @property is not marked as nonatomic, so the getter is not just a simple return, but a lock, retain, autorelease and unlock - for thread safety purposes. You can either write your own getter or declare the property as @property (nonatomic, retain)