標籤:
引用計數和字串 記憶體中的常量字串的空間分配與其他對象不同,他們沒有引用計數機制 凡是自訂的對象都有引用計數機制; OC內部中對象分為可變對象(NSMutableString等)和不可變對象(NSString、NSArray等),不可變對象不適用於引用計數的機制,可變的對象適用引用計數機制。
1 // main.m 2 // 03-unmutableobject 3 // 4 // Created by ma c on 15/8/13. 5 // Copyright (c) 2015年 bjsxt. All rights reserved. 6 // 7 8 #import <Foundation/Foundation.h> 9 10 int main(int argc, const char * argv[])11 {12 @autoreleasepool13 {14 //不可變對象不適用於引用計數15 //1.建立3個對象16 NSString *str1 = @"hello world";//不可變對象17 18 NSString *str2 = [NSString stringWithString:@"how arer you"];//不可變對象19 20 NSMutableString *str3 = [NSMutableString stringWithString:@"I am fine"];//可變對象21 22 NSLog(@"str1 = %lu,str2 = %lu,str3 = %lu",[str1 retainCount],[str2 retainCount],[str3 retainCount]);23 24 25 //2.將3個對象添加到可變數組中26 NSMutableArray *array = [NSMutableArray array];27 [array addObject:str1];28 [array addObject:str2];29 [array addObject:str3];30 NSLog(@"str1 = %lu,str2 = %lu,str3 = %lu",[str1 retainCount],[str2 retainCount],[str3 retainCount]);31 32 33 //3.對3個對象做retain操作34 [str1 retain];35 [str2 retain];36 [str3 retain];37 NSLog(@"str1 = %lu,str2 = %lu,str3 = %lu",[str1 retainCount],[str2 retainCount],[str3 retainCount]);38 39 //4.將3個對象從數組中刪除40 [array removeObject:str1];41 [array removeObject:str2];42 [array removeObject:str3];43 NSLog(@"str1 = %lu,str2 = %lu,str3 = %lu",[str1 retainCount],[str2 retainCount],[str3 retainCount]);44 45 //5.對對象做release操作---對應上面的retain操作46 [str1 release];47 [str2 release];48 [str3 release];49 NSLog(@"str1 = %lu,str2 = %lu,str3 = %lu",[str1 retainCount],[str2 retainCount],[str3 retainCount]);50 51 52 //6.對對象做release操作---對應上面的對象建立操作(避免記憶體泄露)53 [str1 release];54 [str2 release];55 [str3 release];56 }57 return 0;58 }
測試結果是:
2015-08-13 17:41:26.569 03-unmutableobject[1622:105614] str1 = 18446744073709551615,str2 = 18446744073709551615,str3 = 12015-08-13 17:41:26.570 03-unmutableobject[1622:105614] str1 = 18446744073709551615,str2 = 18446744073709551615,str3 = 22015-08-13 17:41:26.571 03-unmutableobject[1622:105614] str1 = 18446744073709551615,str2 = 18446744073709551615,str3 = 32015-08-13 17:41:26.571 03-unmutableobject[1622:105614] str1 = 18446744073709551615,str2 = 18446744073709551615,str3 = 22015-08-13 17:41:26.571 03-unmutableobject[1622:105614] str1 = 18446744073709551615,str2 = 18446744073709551615,str3 = 1Program ended with exit code: 0
說明:可以明顯看出,NSString是不適用引用計數機制的。
Objective-C:MRC(引用計數器)在OC內部的可變對象是適用的,不可變對象是不適用的(例如 NSString、NSArray等)