使用归档程序复制对象

作者:追风剑情 发布于:2019-3-8 16:39 分类:Objective-C

利用归档程序进行深度复制,对于不支持NSCopying协议的对象可用这项技术。

示例

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSData *data;
        NSMutableArray *dataArray = [NSMutableArray arrayWithObjects:
            [NSMutableString stringWithString: @"one"],
            [NSMutableString stringWithString: @"two"],
            [NSMutableString stringWithString: @"three"],
            nil
        ];
        
        NSMutableArray *dataArray2;
        NSMutableString *mStr;
        
        // 使用归档器进行深层复制
        //data = [NSKeyedArchiver archivedDataWithRootObject: dataArray];
        //dataArray2 = [NSKeyedUnarchiver unarchiveObjectWithData: data];
        // 合并成一句代码
        dataArray2 = [NSKeyedUnarchiver unarchiveObjectWithData:
                      [NSKeyedArchiver archivedDataWithRootObject: dataArray]];
        
        mStr = dataArray2[0];
        [mStr appendString: @"ONE"];
        
        NSLog(@"dataArray: ");
        for (NSString *elem in dataArray)
            NSLog(@"%@", elem);
        
        NSLog(@"dataArray2: ");
        for (NSString *elem in dataArray2)
            NSLog(@"%@", elem);
    }
    return 0;
}
运行测试
111.png

标签: Objective-C

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号