超简易复制Model对象(为后续备忘录设计模式博文做铺垫)
复制整个Model需要实现NSCopy协议,可以想象是非常麻烦的一件事情,今天我跟大家分享一个不需要你做任何操作的复制Model对象的方法,不过,首先你得先去下载开源代码FastCoder辅助才行。
源码如下:
NSObject+ObjectCopy.h 与 NSObject+ObjectCopy.m
// // NSObject+ObjectCopy.h // FastCoder // // Created by YouXianMing on 15/1/3. // Copyright (c) 2015年 YouXianMing. All rights reserved. // #import <Foundation/Foundation.h> @interface NSObject (ObjectCopy) /** * 复制对象 * * @return 返回复制的对象 */ - (id)copyObject; @end
// // NSObject+ObjectCopy.m // FastCoder // // Created by YouXianMing on 15/1/3. // Copyright (c) 2015年 YouXianMing. All rights reserved. // #import "NSObject+ObjectCopy.h" #import "FastCoder.h" @implementation NSObject (ObjectCopy) - (id)copyObject { id object = nil; NSData *data = nil; if ((data = [FastCoder dataWithRootObject:self])) { object = [FastCoder objectWithData:data]; } return object; } @end
Model.h 与 Model.m
// // Model.h // FastCoder // // Created by YouXianMing on 15/1/3. // Copyright (c) 2015年 YouXianMing. All rights reserved. // #import <Foundation/Foundation.h> @interface Model : NSObject @property (nonatomic, strong) NSString *name; // 姓名 @property (nonatomic, strong) NSNumber *age; // 年龄 @property (nonatomic, strong) NSDate *birthDate; // 出身日期 @property (nonatomic, strong) NSArray *subInfo; // 子信息 @property (nonatomic, strong) NSDictionary *address; // 地址 - (void)info; @end
// // Model.m // FastCoder // // Created by YouXianMing on 15/1/3. // Copyright (c) 2015年 YouXianMing. All rights reserved. // #import "Model.h" @implementation Model - (void)info { NSLog(@"[%@]", self); NSLog(@"name %@", self.name); NSLog(@"age %@", self.age); NSLog(@"birthDate %@", self.birthDate); NSLog(@"subInfo %@", self.subInfo); NSLog(@"address %@", self.address); NSLog(@""); } @end
控制器源码:
// // ViewController.m // http://home.cnblogs.com/u/YouXianMing/ // // Created by YouXianMing on 15/1/3. // Copyright (c) 2015年 YouXianMing. All rights reserved. // #import "ViewController.h" #import "NSObject+ObjectCopy.h" #import "Model.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // ModelOne Model *model_one = [Model new]; model_one.name = @"YouXianMing"; model_one.age = @(27); model_one.birthDate = [NSDate date]; model_one.subInfo = @[@"iOS", @"C++"]; model_one.address = @{@"BeiJing": @"TongZhou"}; [model_one info]; // ModelTwo Model *model_two = [model_one copyObject]; model_two.name = @"QiuLiang"; model_two.age = @(28); [model_two info]; } @end
核心的地方: