前两天跟同事争论一个关于NSString执行copy操作以后是否会发生变化,两个人整了半天,最后写代码验证了一下,发现原来NSString操作没我们想的那么简单,下面就让我们一起看看NSString和NSMutableString在MRC下执行retain,copy,mutableCopy,以及ARC下不同的修饰__weak, __strong修饰赋值究竟发生了什么。
一、验证代码如下:
- (void)testStringAddress { int a = 0; int b = 0; static int c = 0; NSString *str = @"Hello World"; #if __has_feature(objc_arc) __weak NSString *weakStr = str; __strong NSString *strongStr = str; #else NSString *retainStr = [str retain]; #endif NSString *copyStr = [str copy]; NSMutableString *mutableCopyStr = [str mutableCopy]; // 验证mutableCopy出来的是否是mutableString,如果不是执行此行会Crash [mutableCopyStr appendFormat:@".."]; str = @"i'm changed"; NSString *str2 = [NSString stringWithFormat:@"Hello world"]; #if __has_feature(objc_arc) __weak NSString *weakStr2 = str2; __strong NSString *strongStr2 = str2; #else NSString *retainStr2 = [str2 retain]; #endif NSString *copyStr2 = [str2 copy]; NSString *copy2Str2 = [str2 copy]; NSString *mutableCopyStr2 = [str2 mutableCopy]; NSString *mutableCopy2Str2 = [str mutableCopy]; str2 = [[NSString alloc] initWithFormat:@"changed"]; NSMutableString *mutableStr = [NSMutableString stringWithString:@"hello world"]; #if __has_feature(objc_arc) __weak NSMutableString *weakMutableStr = mutableStr; __strong NSMutableString *strongMutableStr = mutableStr; #else NSMutableString *retainMutableStr = [mutableStr retain]; #endif NSMutableString *copyMutableStr = [mutableStr copy]; NSMutableString *copy2MutableStr = [mutableStr copy]; NSString *mutableCopyMutableStr = [mutableStr mutableCopy]; NSString *mutableCopy2MutableStr = [mutableStr mutableCopy]; [mutableStr appendFormat:@" apped something"]; #if __has_feature(objc_arc) NSLog(@"\r str: %@,\r weakStr: %@,\r strongStr: %@,\r copyStr: %@,\r mutableCopyStr: %@", str, weakStr, strongStr, copyStr, mutableCopyStr); NSLog(@"\r str2: %@,\r weakStr2: %@,\r strongStr: %@,\r copyStr2: %@,\r mutableCopyStr2: %@", str2, weakStr2, strongStr2, copyStr2, mutableCopyStr2); NSLog(@"\r mutableStr: %@,\r weakMutableStr: %@\r strongMutableStr: %@,\r copyMutableStr: %@,\r mutableCopyMutableStr: %@", mutableStr, weakMutableStr, strongMutableStr, copyMutableStr, mutableCopyMutableStr); #else NSLog(@"\r str: %@,\r retainStr: %@,\r copyStr: %@,\r mutableCopyStr: %@", str, retainStr, copyStr, mutableCopyStr); NSLog(@"\r str2: %@,\r retainStr2: %@,\r copyStr2: %@,\r mutableCopyStr2: %@", str2, retainStr2, copyStr2, mutableCopyStr2); NSLog(@"\r mutableStr: %@,\r retainMutableStr: %@,\r copyMutableStr: %@,\r mutableCopyMutableStr: %@", mutableStr, retainMutableStr, copyMutableStr, mutableCopyMutableStr); #endif }