請檢查下面的代碼:爲什麼在原始NSString對象被釋放後NSString的lowercaseString沒有被釋放?
CFUUIDRef uuid=CFUUIDCreate(kCFAllocatorDefault);
NSString *strUuid=(NSString *)CFUUIDCreateString(kCFAllocatorDefault,uuid);
NSString *lowerUuid=[strUuid lowercaseString];
NSLog(@"strUuid retainCount:%tu",[strUuid retainCount]);
CFRelease(strUuid);
CFRelease(uuid);
NSLog(@"lowerUuid retainCount:%tu",[lowerUuid retainCount]);
NSLog(@"lowerUuid:%@",lowerUuid);
運行這段代碼在非弧項目,輸出將是:
strUuid retainCount:1
lowerUuid retainCount:1
lowerUuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
lowercaseString是的NSString的一個屬性,它的定義是:
@property (readonly, copy) NSString *lowercaseString;
所以有理由推斷,如果原始NSString對象被釋放,則在NSString的dealloc方法中將釋放lowercaseString屬性。 但是爲什麼在上面的代碼中,即使原始strUuid被釋放後,lowerUuid仍然存在?
我不認爲這是一個合理的推論。 'copy'屬性可能意味着返回的值是原始字符串的副本,並附有自己的保留計數。 – 2014-10-18 01:31:53