2013-05-01 69 views
4

這裏是我的代碼:爲什麼__weak限定符的變量保留一個對象?

extern void _objc_autoreleasePoolPrint(); 

int main(int argc, const char * argv[]) 
{ 

    NSArray __weak *tmp = nil; 

    @autoreleasepool { 

     NSArray __strong *obj = [[NSArray alloc] init]; 

     NSLog(@"obj &: %p", obj); 

     tmp = obj; 

     NSLog(@"tmp &: %p", tmp); 

     _objc_autoreleasePoolPrint(); 
    } 

    NSLog(@"tmp: %@", tmp); // why not (null) ? 


    return 0; 
} 

和控制檯輸出:

2013-05-01 22:14:32.966 SimpleConsoleObjectiveCApplicationWithARC[40660:f07] obj &: 0x7fedf9403110 
2013-05-01 22:14:32.969 SimpleConsoleObjectiveCApplicationWithARC[40660:f07] tmp &: 0x7fedf9403110 
objc[40660]: ############## 
objc[40660]: AUTORELEASE POOLS for thread 0x7fff751af180 
objc[40660]: 2 releases pending. 
objc[40660]: [0x7fedf9805000] ................ PAGE (hot) (cold) 
objc[40660]: [0x7fedf9805038] ################ POOL 0x7fedf9805038 
objc[40660]: [0x7fedf9805040] 0x7fedf9403110 __NSArrayI 
objc[40660]: ############## 
2013-05-01 22:14:32.971 SimpleConsoleObjectiveCApplicationWithARC[40660:f07] tmp: (
) 

PS#1

改變的NSArray到NSMutableArray裏和TMP變量變成零。

extern void _objc_autoreleasePoolPrint(); 

int main(int argc, const char * argv[]) 
{ 

    NSMutableArray __weak *tmp = nil; 

    @autoreleasepool { 

     NSMutableArray __strong *obj = [[NSMutableArray alloc] init]; 

     NSLog(@"obj &: %p", obj); 

     tmp = obj; 

     NSLog(@"tmp &: %p", tmp); 

     _objc_autoreleasePoolPrint(); 
    } 

    NSLog(@"tmp: %@", tmp); 


    return 0; 
} 

有人可以解釋我爲什麼這樣工作嗎?

回答

5

似乎[[NSArray alloc] init]返回空NSArray的「共享實例」:

NSArray *a = [[NSArray alloc] init]; 
NSArray *b = [[NSArray alloc] init]; 
NSLog(@"a &: %p", a); 
NSLog(@"b &: %p", b); 

輸出:

 
    a &: 0x100103110 
    b &: 0x100103110 

這種「共享實例」繼續存在,即使你很強的參考obj是因此 因此弱指針未設置爲nil

顯然,[[NSMutableArray alloc] init]無法返回共享實例。

+0

Martin R,是的,所有不可變的類都返回「共享實例」(檢查過NSString,NSDictionary等),但有什麼辦法可以傳遞這個「特性」嗎? – AndrewShmig 2013-05-01 18:55:00

+2

@AndrewShmig:你想達到什麼目的?爲什麼你需要弱參考成爲零? – 2013-05-01 19:00:09

+0

馬丁R,我想明白爲什麼__weak不能正常工作,因爲它預計在變量obj離開它的範圍後工作。 – AndrewShmig 2013-05-02 05:51:14

相關問題