簡體   English   中英

參考計數或保留計數問題(內存管理)

[英]Reference Count or Retain Count Issue (Memory Management)

以下代碼可以正常運行,您可以在系統上運行以進行確認。

如您所見,我的問題是,僅當保留計數達到零時才調用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

這並不奇怪, 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讀取的值。 這只是一個實現細節。 retainrelease視為所有權轉移的考慮要安全得多。

retainCount文檔中:

不要使用此方法。

此方法對於調試內存管理問題沒有任何價值。 (...)從此方法獲取有用信息的可能性很小。

將您的項目切換到ARC。 說真的 我忘記了三年前關於保留/釋放的所有知識。 除此之外,對象在釋放過程中的保留計數是沒有意義的 對此毫無意義

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM