-
非容器类对象
1 . imutable对象
NSString *string = @"origion";
NSString *stringCopy = [string copy];
NSMutableString *stringMCopy = [string mutableCopy];
[stringMCopy appendString:@"!!"];
string
和stringCopy
指向同一段内存,即浅拷贝。而mutableCopy内存变化,为深拷贝
2 . mutable对象
NSMutableString *string = [NSMutableString stringWithString: @"origion"];
NSString *stringCopy = [string copy];
NSMutableString *mStringCopy = [string copy];
NSMutableString *stringMCopy = [string mutableCopy];
// [mStringCopy appendString:@"mm"];//error -----> A
[string appendString:@" origion!"];
[stringMCopy appendString:@"!!"];
string
和stringCopy
和mStringCopy
和stringMCopy
四段内存地址都不一样,对于mStringCopy
实际上是imutable对象,所以 A
段代码会报错,因为修改了imutable对象。所以对于 mutable对象(非容器类)copy和mutableCopy都是深拷贝,但是前者返回的对象imutable,不可修改
- 容器类对象
- imutable容器
NSArray *array = @[@"1",@"2",@"3"];
NSArray *arrayCopy = [array copy];
NSMutableArray *arrayMCopy = [array mutableCopy];
//[arrayMCopy addObject:@"4"];
//[arrayMCopy removeObjectAtIndex:0];
NSLog(@"obj address in array:%p at index 0 : %p",array, array[1]);
NSLog(@"obj address in arrayCopy:%p at index 0 : %p",arrayCopy, arrayCopy[1]);
NSLog(@"obj address in mArrayCopy:%p at index 0 : %p",arrayMCopy, arrayMCopy[1]);
我们再看个例子
NSArray *array2 = @[[NSMutableString stringWithString:@"a"],
@"b",
@"c"];
NSArray *arrayCopy2 = [array2 copy];
NSMutableArray *arrayMCopy2 = [array2 mutableCopy];
NSLog(@"obj address in array2:%p at index 0 : %p",array2, array2[0]);
NSLog(@"obj address in arrayCopy2:%p at index 0 : %p",arrayCopy2, arrayCopy2[0]);
NSLog(@"obj address in arrayMCopy2:%p at index 0 : %p",arrayMCopy2, arrayMCopy2[0]);
可见 对imutable对象进行copy
是指针复制,进行mutableCopy
是对象复制,但是容器内容始终都是指针复制
2 . mutable容器
NSMutableArray *mArray3 = [NSMutableArray arrayWithArray:@[@"1",
@"2",
@"3"]];
NSArray *mArrayCopy3 = [mArray3 copy];
NSMutableArray *mArrayMCopy3 = [mArray3 mutableCopy];
NSLog(@"obj address in mArray3:%p at index 0 : %p",mArray3, mArray3[1]);
NSLog(@"obj address in mArrayCopy3:%p at index 0 : %p",mArrayCopy3, mArrayCopy3[1]);
NSLog(@"obj address in mArrayMCopy3:%p at index 0 : %p",mArrayMCopy3, mArrayMCopy3[1]);
对于mutable容器,copy
亦或是mutableCopy
对于容器都是对象拷贝,对于容器内容都是指针拷贝,并且copy
返回imutable对象,mutableCopy
返回mutable对象
总结:
| copy | mutablecopy
----|------|----
不可变非容器对象 | 浅拷贝 | 深拷贝
可变非容器对象 | 深拷贝(返回不可变对象) | 深拷贝(返回可变对象)
不可变容器对象(容器内容始终指针复制) | 浅拷贝(返回不可变对象) | 深拷贝(返回可变对象)
可变容器对象(容器内容始终指针复制) | 深拷贝(返回不可变对象) | 深拷贝(返回可变对象)