介绍 :
NSCFConstantString (retain/release不起作用,系统进行维护,程序中内容相同的常量字符串只有一个)
NSCFString (retain/release有作用)
NSTaggedPointerString (retain/release不起作用)
验证代码
NSString *str = @"test";
NSLog(@"str--->%ld",[str retainCount]); // NSCFConstanString 类型
NSString *str1 = [@"test" copy];
NSLog(@"str1--->%ld",[str1 retainCount]); // NSCFConstanString
// 拷贝后是可变类型
NSString *str2 = [@"test" mutableCopy];
NSLog(@"str2--->%ld",[str2 retainCount]); // NSCFString
NSString *str3 = [NSString stringWithString:@"test"];
NSLog(@"str3--->%ld",[str3 retainCount]); // NSCFConstanString
NSString *str4 = [NSString stringWithFormat:@"%@",@"test"];
NSLog(@"str4--->%ld",[str4 retainCount]); // NSTaggedPointerString
NSString *str5 = [[NSString alloc] initWithString:@"Hello World"];
NSLog(@"str5--->%ld",[str5 retainCount]); // NSCFConstanString
NSString* str6 = [[NSString alloc] initWithFormat:@"%@",@"Hello World"];
NSLog(@"str6--->%ld",[str6 retainCount]); // NSCFString
// 本质上还是不可变类型
NSMutableString *mutableStr = [@"test" copy];
NSLog(@"mutableStr--->%ld",[mutableStr retainCount]); // NSCFConstanString
NSMutableString *mutableStr1 = [@"test" mutableCopy];
NSLog(@"mutableStr1--->%ld",[mutableStr1 retainCount]); // NSCFString
NSMutableString *mutableStr2 = [NSMutableString stringWithString:@"test"];
NSLog(@"mutableStr2--->%ld",[mutableStr2 retainCount]); // NSCFString
NSMutableString *mutableStr3 = [NSMutableString stringWithFormat:@"%@",@"test"];
NSLog(@"mutableStr3--->%ld",[mutableStr3 retainCount]); // NSCFString
NSMutableString *mutableStr4 = [[NSMutableString alloc]initWithString:@"test"];
NSLog(@"mutableStr4--->%ld",[mutableStr4 retainCount]); // NSCFString
NSMutableString *mutableStr5 = [[NSMutableString alloc]initWithFormat:@"%@",@"test"];
NSLog(@"mutableStr5--->%ld",[mutableStr5 retainCount]); // NSCFString
输出 :
2018-09-23 10:38:08.187 LZX_Test001[2713:191391] str--->-1
2018-09-23 10:38:08.188 LZX_Test001[2713:191391] str1--->-1
2018-09-23 10:38:08.188 LZX_Test001[2713:191391] str2--->1
2018-09-23 10:38:08.188 LZX_Test001[2713:191391] str3--->-1
2018-09-23 10:38:08.188 LZX_Test001[2713:191391] str4--->-1
2018-09-23 10:38:08.189 LZX_Test001[2713:191391] str5--->-1
2018-09-23 10:38:08.189 LZX_Test001[2713:191391] str6--->1
2018-09-23 10:53:03.549 LZX_Test001[2757:198382] mutableStr--->-1
2018-09-23 10:53:03.549 LZX_Test001[2757:198382] mutableStr1--->1
2018-09-23 10:53:03.550 LZX_Test001[2757:198382] mutableStr2--->1
2018-09-23 10:53:03.550 LZX_Test001[2757:198382] mutableStr3--->1
2018-09-23 10:53:03.550 LZX_Test001[2757:198382] mutableStr4--->1
结论 :
1. 只有NSCFString 类型指针才会参与引用计数
2. NSString使用initWithFormat创建是NSCFString类型指针