0

以下代码工作正常,您可以在系统上运行它以进行确认。

我的问题是,如您所见,仅当保留计数达到零时才调用 dealloc 方法,这意味着为 RetainTracker 对象释放了内存。但是,问题是当我在 dealloc 方法中记录保留计数时,它仍然显示保留计数为 1。这是为什么呢?

这是我的代码:

#import <Foundation/Foundation.h>
@interface RetainTracker : NSObject

@end

@implementation RetainTracker

- (id)init {

    if (self = [super init]) {
        NSLog(@"init: Retain count of %lu",(unsigned long)[self retainCount]);
    }
    return self;
}

- (void)dealloc {

    NSLog(@"Dealloc called bye bye!==>%lu",(unsigned long)self.retainCount);
    [super dealloc];
}

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        RetainTracker *myRetainTracker = [RetainTracker new];

        [myRetainTracker retain]; // count-->2
        NSLog(@"The retain count is ==>%lu",(unsigned long)myRetainTracker.retainCount);

        [myRetainTracker release];// count -->1
        NSLog(@"The retain count is ==>%lu",(unsigned long)myRetainTracker.retainCount);

        [myRetainTracker retain];// count -->2
        NSLog(@"The retain count is ==>%lu",(unsigned long)myRetainTracker.retainCount);

        [myRetainTracker release];// count -->1
        NSLog(@"The retain count is ==>%lu",(unsigned long)myRetainTracker.retainCount);

        [myRetainTracker release];// count -->0
        NSLog(@"The retain count is ==>%lu",(unsigned long)myRetainTracker.retainCount);

    }
    return 0;
}

以下是日志:

init: Retain count of 1
The retain count is ==>2
The retain count is ==>1
The retain count is ==>2
The retain count is ==>1
Dealloc called bye bye!==>1
The retain count is ==>1
4

2 回答 2

3

这并不奇怪,release代码可能看起来像这样(伪代码):

- (void)release {
   if (retainCount > 1) {
      retainCount -= 1
   } else {
      // no need to set the retainCount to 0 here,
      // the object now ends its existence
      [self dealloc]
   }
}

此外,您的最后一个NSLog实际上是访问一个不再存在的对象,这可能导致崩溃。

retainCount请注意,永远不应依赖从中读取的值。这只是一个实现细节。retain将其release视为所有权转移更为安全。

retainCount文档:

不要使用这种方法。

这种方法在调试内存管理问题时没有任何价值。(...) 您不太可能从这种方法中获得有用的信息。

于 2016-05-21T10:52:32.610 回答
-1

将您的项目切换到 ARC。严重地。我已经忘记了三年前我所知道的关于保留/释放的一切。除此之外,对象在被释放过程中的保留计数是没有意义的。想知道它是没有意义的。

于 2016-05-21T10:31:38.743 回答