0

代碼對象:註冊創建外@autoreleasepool塊和奇怪的__weak指針行爲

@autoreleasepool { 

     id __autoreleasing obj = nil; 

     @autoreleasepool { 
      obj = [[NSObject alloc] init]; 

      _objc_autoreleasePoolPrint(); 
     } 

     NSLog(@"obj: %@", obj); // Error 
     _objc_autoreleasePoolPrint(); 
    } 

從鏘文檔:

For __autoreleasing objects, the new pointee is retained, autoreleased, and stored into the lvalue using primitive semantics. 

爲什麼obj是在內部@autoreleasepool塊外沒有自動釋放?

第二個例子:

@autoreleasepool { 

     id __weak obj = nil; 

     @autoreleasepool { 
      id __strong obj1 = [[NSObject alloc] init]; 
      obj = obj1; 

      NSLog(@"obj: %@", obj); // <NSObject: 0x7857657> 
      NSLog(@"obj retain count: %d", (int) _objc_rootRetainCount(obj1)); // 2 

      _objc_autoreleasePoolPrint(); 
     } 

     NSLog(@"obj retain count: %d", (int) _objc_rootRetainCount(obj)); // 1 
     NSLog(@"obj: %@", obj); // (null) 

     _objc_autoreleasePoolPrint(); 
    } 

爲什麼的NSLog輸出 「(空)」 如果保留計數是1?

回答

1

爲什麼obj在內部@autoreleasepool塊中自動釋放而不在外部?

該目的是自動釋放在分配到objobj = [[NSObject alloc] init];),因此它被放入最上層(最裏面的)自動釋放池,並且當該池排出被解除(在@autoreleasepool塊的結尾)。

爲什麼如果保留計數爲1,NSLog輸出「(null)」?

_objc_rootRetainCount()不是記錄功能。顯然_objc_rootRetainCount(nil)評估爲1.

+0

好的。謝謝。但我沒有得到答案爲什麼(空)正在打印。 – AndrewShmig 2013-05-13 04:05:14

+0

@AndrewShmig:因爲'obj'爲null('nil') – newacct 2013-05-13 05:01:28