开发者

Retain count of a synthesized property

开发者 https://www.devze.com 2023-02-28 19:39 出处:网络
Please review my code: @interface ClassA : NSObject { ClassB *objB; } @property (retain) ClassB *objB; @end

Please review my code:

@interface ClassA : NSObject {
    ClassB *objB;
}

@property (retain) ClassB *objB;
@end

@implementation ClassA:
@synth开发者_如何学编程esiaze 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!


Apple has this to say about retainCount:

Important: This method is typically of no value in debugging memory management issues. Because any number of framework objects may have retained an object in order to hold references to it, while at the same time autorelease pools may be holding any number of deferred releases on an object, it is very unlikely that you can get useful information from this method.

To understand the fundamental rules of memory management that you must abide by, read “Memory Management Rules”.

Don't worry about retain counts; just worry about calling release if you call retain, alloc, or a method whose name starts with copy, mutableCopy, or new.


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:

- (ClassB *)objB
{
    return [[objB retain] autorelease];
}

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.


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消