OC的NSString、NSArray、NSDictionary、NS*、NSMu等都具有拷贝功能。
拷贝有浅拷贝copy、深拷贝mutableCopy
字符串拷贝
//字符串
NSString *str = @"test";
NSString *str1 = [str copy];
NSMutableString *str2 = [str mutableCopy];
NSLog(@"str = %@, str1 = %@, str2 = %@", str, str1, str2);
NSLog(@"str = %p, str1 = %p, str2 = %p", str, str1, str2);
输出内容:
str = test, str1 = test, str2 = test
str = 0x10cf1a0c0, str1 = 0x10cf1a0c0, str2 = 0x6000007ba8b0
从控制台输出结果可以看出:copy、mutableCopy都可以输出内容,但是内存地址上面看,copy的内存地址与原数据相同为浅拷贝,mutableCopy地址与原对象不同为深拷贝。
可变字符串拷贝
//可变字符串
NSMutableString *muStr = [[NSMutableString alloc] initWithString:@"muTest"];
NSString *muStr1 = [muStr copy];
NSString *muStr2 = [muStr mutableCopy];
NSLog(@"muStr = %@, muStr1 = %@, muStr2 = %@", muStr, muStr1, muStr2);
NSLog(@"muStr = %p, muStr1 = %p, muStr2 = %p", muStr, muStr1, muStr2);
输出结果:
muStr = muTest, muStr1 = muTest, muStr2 = muTest
muStr = 0x6000007ba970, muStr1 = 0xa88d52e5e8840e6a, muStr2 = 0x6000007ba6d0
从控制台输出结果可以看出:copy、mutableCopy都可以输出,但是内存地址和原对象都不同,所以可变字符串拷贝出来的都是深拷贝。
从上面可以看出:
NSString,copy出来的对象是浅拷贝,即指针拷贝;通过mutableCopy操作出的对象是深拷贝,即内容拷贝。
NSMutableString, copy与mutableCopy拷贝出来的对象都是深拷贝,即内容拷贝。