引用计数和字符串
内存中的常量字符串的空间分配与其他对象不同,他们没有引用计数机制
凡是自定义的对象都有引用计数机制;
OC内部中对象分为可变对象(NSMutableString等)和不可变对象(NSString、NSArray等),
不可变对象不适用于引用计数的机制,可变的对象适用引用计数机制。
1 // main.m 2 // 03-unmutableobject 3 // 4 // Created by ma c on 15/8/13. 5 // Copyright (c) 2015年. All rights reserved. 6 // 7 8 #import <Foundation/Foundation.h> 9 10 int main(int argc, const char * argv[]) 11 { 12 @autoreleasepool 13 { 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 = 1 2015-08-13 17:41:26.570 03-unmutableobject[1622:105614] str1 = 18446744073709551615,str2 = 18446744073709551615,str3 = 2 2015-08-13 17:41:26.571 03-unmutableobject[1622:105614] str1 = 18446744073709551615,str2 = 18446744073709551615,str3 = 3 2015-08-13 17:41:26.571 03-unmutableobject[1622:105614] str1 = 18446744073709551615,str2 = 18446744073709551615,str3 = 2 2015-08-13 17:41:26.571 03-unmutableobject[1622:105614] str1 = 18446744073709551615,str2 = 18446744073709551615,str3 = 1 Program ended with exit code: 0
说明:可以明显看出,NSString是不适用引用计数机制的。
程序猿神奇的手,每时每刻,这双手都在改变着世界的交互方式!
本文转自当天真遇到现实博客园博客,原文链接:http://www.cnblogs.com/XYQ-208910/p/4728026.html,如需转载请自行联系原作者