ios面试题iOS入职集锦

iOS 单层深复制与完全深复制

2018-12-28  本文已影响12人  devmao

概念

浅复制示意图 深复制示意图

结论

1、非集合对象的copy与mutableCopy

2、集合对象的copy与mutableCopy

集合对象与非集合对象所遵循的规则基本上是一样的,唯一差别:
集合对象的深复制并不是严格意义上的深复制,而是单层深复制。

单层深复制:对集合对象来说,深复制时只是将第一层对象进行了深复制,内部的对象仍然是浅复制。

3、集合对象的完全复制

代码及运行结果如下:

#import <Foundation/Foundation.h>

@interface ModelStudent : NSObject<NSCopying>

@property(nonatomic, copy) NSString * name;

@property(nonatomic, assign) NSInteger  age;

@property(nonatomic, assign) NSInteger sex;

@end
#import "ModelStudent.h"

@implementation ModelStudent

- (id)copyWithZone:(NSZone *)zone{
    ModelStudent * s = [[ModelStudent alloc]init];
    s.name = self.name;
    s.age = self.age;
    s.sex = self.sex;
    return s;
}

@end
    ModelStudent * model1 = [ModelStudent new];
    model1.name = @"mao";
    model1.age = 14;

    ModelStudent * model2 = [ModelStudent new];
    model2.name = @"mao";
    model2.age = 14;
    
    self.arr = @[model1, model2];
    
    //完全深复制
    NSArray * array4 = [[NSArray alloc]initWithArray:self.arr copyItems:YES];
    NSLog(@"%@,%@", self.arr, array4);
运行结果
#import <Foundation/Foundation.h>

@interface ModelStudent : NSObject<NSCoding>

@property(nonatomic, copy) NSString * name;

@property(nonatomic, assign) NSInteger  age;

@property(nonatomic, assign) NSInteger sex;

@end
#import "ModelStudent.h"

@implementation ModelStudent

- (void)encodeWithCoder:(NSCoder *)aCoder{

    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:@(self.age) forKey:@"age"];
    [aCoder encodeObject:@(self.sex) forKey:@"sex"];
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super init]) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.age = [[aDecoder decodeObjectForKey:@"age"] integerValue];
        self.sex = [[aDecoder decodeObjectForKey:@"sex"] integerValue];
    }
    return self;
}

@end
ModelStudent * model1 = [ModelStudent new];
    model1.name = @"mao";
    model1.age = 14;
    
    ModelStudent * model2 = [ModelStudent new];
    model2.name = @"mao";
    model2.age = 14;
    
    self.arr = @[model1, model2];
    
    NSMutableArray * arr2 = [self.arr mutableCopy];
    //完全深复制
    //先归档
    NSMutableArray * mDatas = [NSMutableArray arrayWithCapacity:0];
    for (ModelStudent * model in self.arr) {
        NSData * data = [NSKeyedArchiver archivedDataWithRootObject:model];
        [mDatas addObject:data];
    }
    //再解档
    NSMutableArray * mModels = [NSMutableArray arrayWithCapacity:0];
    for (NSData * data in mDatas) {
        ModelStudent * model = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        [mModels addObject:model];
    }
    
    NSLog(@"非完全深复制:%@---%@", self.arr, arr2);
    NSLog(@"完全深复制:%@---%@", self.arr, mModels);
打印结果

参考

iOS中的深复制与浅复制
NSObject 有个copyWithZone是什么作用?
iOS学习笔记系列 - OC如何正确重写copyWithZone

上一篇下一篇

猜你喜欢

热点阅读