介紹 :
NSCFConstantString (retain/release不起作用,系統(tǒng)進(jìn)行維護(hù),程序中內(nèi)容相同的常量字符串只有一個)
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
// 本質(zhì)上還是不可變類型
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
結(jié)論 :
1. 只有NSCFString 類型指針才會參與引用計數(shù)
2. NSString使用initWithFormat創(chuàng)建是NSCFString類型指針