OC浅拷贝、深拷贝和完全拷贝

浅拷贝:仅仅对内存地址进行了拷贝,并没有对源对象进行拷贝。

深拷贝:不仅对内存地址进行拷贝,而且对源对象进行拷贝。

完全深拷贝:在拷贝的时候,被拷贝对象的每一层都进行了拷贝。



多层集合对象的完全拷贝

student.h


//
//  student.h
//  TEST
//
//  Created by liuyinghui on 2018/3/1.
//  Copyright © 2018年 liuyinghui. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface student : NSObject
@property NSString *name;
@property NSInteger  age;
@end

student.m



//
//  student.m
//  TEST
//
//  Created by liuyinghui on 2018/3/1.
//  Copyright © 2018年 liuyinghui. All rights reserved.
//

#import "student.h"

@interface student ()<NSCoding,NSCopying>

@end
@implementation student

- (id)copyWithZone:(nullable NSZone *)zone{
    student* copy= [[[self class] allocWithZone:zone] init];
    copy.name=[self.name mutableCopy];
    copy.age=self.age;
    return copy;
}



- (void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInteger:self.age forKey:@"age"];
}
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder{
    _name=[aDecoder decodeObjectForKey:@"name"];
    _age=[aDecoder decodeIntegerForKey:@"age"];
    return self;
}

@end
    NSMutableArray *array=[[NSMutableArray alloc] init];
    student *stu=[[student alloc] init];
    stu.name=[NSString stringWithFormat:@"lisi"];
    stu.age=9;
    [array addObject:stu];
    //方式1 要在集合对象中实现NSCoding协议
//    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];
//    NSArray *array2 = [NSKeyedUnarchiver unarchiveTopLevelObjectWithData:data error:nil];
    
    //方式2 要在集合对象中实现NSCopying协议
    NSMutableArray *array2=[[NSMutableArray alloc] initWithArray:array copyItems:YES];
    student*stu1=[array firstObject];
    student *stu2=[array2 firstObject];
    NSLog(@"array %p--%@",array,stu1.name);
    NSLog(@"array2 %p--%@",array2,stu2.name);


猜你喜欢

转载自blog.csdn.net/liuyinghui523/article/details/79411652
今日推荐