深复制 浅复制
2015-12-20 22:52 AB小博客 阅读(192) 评论(0) 编辑 收藏 举报深复制:不仅复制对象 还复制对象关联的对象
浅复制:只是复制对象本身 不复制对象关联的对象
// // main.m // 对象的复制 // // Created by MAC on 15/12/20. // Copyright © 2015年 MAC. All rights reserved. // #import <Foundation/Foundation.h> #import "Person.h" int main(int argc, const char * argv[]) { @autoreleasepool { //深复制 把对象关联的对象也复制 NSMutableString *m1 = [NSMutableString stringWithString:@"one"]; NSMutableString *m2 = [NSMutableString stringWithString:@"two"]; NSMutableString *m3 = [NSMutableString stringWithString:@"three"]; NSMutableArray *arr = [NSMutableArray arrayWithCapacity:10]; [arr addObject:m1]; [arr addObject:m2]; [arr addObject:m3]; NSMutableArray *arr1 = [arr mutableCopy];//只是赋值对象本身 关联的对象不复制 浅复制 NSLog(@"%@",arr); NSLog(@"%@",arr1); // [arr removeObject:@"one"]; //删除字符串不会影响 [arr1 removeAllObjects]; for (NSObject *s in arr) { //深复制 NSObject *temp = [s mutableCopy]; //把里面的对象拿出来复制给另一个数组 [arr1 addObject:temp]; } [m1 insertString:@"changed" atIndex:1]; //浅复制情况下改变数组的关联对象也会受影响 但深复制不受影响 NSLog(@"%@",arr); NSLog(@"%@",arr1); // //浅复制 // // copy // //mutableCopy 可变的 NSMutableString *str = [NSMutableString stringWithString:@"Hello World"]; NSMutableString *str2 = str; NSLog(@"%p",str); NSLog(@"%p",str2); [str insertString:@"Changed" atIndex:3]; //修改第一个第二个String也被修改 因为内存地址一样 NSLog(@"%@",str); NSLog(@"%@",str2); // NSMutableArray *array = [NSMutableArray arrayWithCapacity:10]; [array addObject:@"1"]; [array addObject:@"2"]; [array addObject:@"3"]; NSMutableArray *array2 = array; //内存地址一样 NSLog(@"%p",array); NSLog(@"%p",array2); [array removeObject:@"2"]; array2 = [array mutableCopy]; //copy内存地址不一样 NSLog(@"%p",array); NSLog(@"%p",array2); // // //自定义对象复制 Person *per = [[Person alloc]init]; per->age = 20; Person *p2 = per; //内存地址一样 NSString Person *p3 = [per copy]; //-[Person copyWithZone:]: unrecognized selector sent to instance 没有找到此方法 需要实现NSCopying协议里面的- (id)copyWithZone:(nullable NSZone *)zone;方法 NSLog(@"=%p",per); NSLog(@"=%p",p3); NSLog(@"%d",p2->age); per->age = 10; NSLog(@"%d",p2->age); NSMutableSet *mset = [NSMutableSet setWithCapacity:10]; [mset addObject:@"one"]; [mset addObject:@"two"]; [mset addObject:@"three"]; [mset addObject:@"four"]; NSMutableSet *mset2 = [mset mutableCopy]; //使用mutableCopy 内存地址不一样 NSLog(@"%p",mset); NSLog(@"%p",mset2); } return 0; }
// // Person.h // 对象的复制 // // Created by MAC on 15/12/20. // Copyright © 2015年 MAC. All rights reserved. // #import <Foundation/Foundation.h> @interface Person : NSObject<NSCopying> { @public int age; } @property(nonatomic)int age; @property(nonatomic,copy)NSString *name; @property(nonatomic)int num; @end // // Person.m // 对象的复制 // // Created by MAC on 15/12/20. // Copyright © 2015年 MAC. All rights reserved. // #import "Person.h" @implementation Person - (id)copyWithZone:(nullable NSZone *)zone{ Person *per = [[Person allocWithZone:zone]init]; NSLog(@"copy per"); return per; } @end