iOS SDK详解之NSCopying协议

原创blog,转载请注明出处
http://blog.csdn.net/hello_hwc?viewmode=contents
欢迎关注我的iOS SDK详解专栏
http://blog.csdn.net/column/details/huangwenchen-ios-sdk.html

前言:NSCopy协议是对对象进行拷贝的协议。Copy后的对象和原对象是两个对象,要分开考虑其生命周期。Copy后的对象应当对原始对象不依赖,不影响。
使用NSCopy协议只需要实现一个方法copyWithZone:即可

举例

OC

@interface MyModel:NSObject<NSCopying>
@property (copy,nonatomic)NSString * name;
@property (nonatomic)int age;
@end

@implementation MyModel

-(instancetype)copyWithZone:(NSZone *)zone{
    MyModel * copyedModel = [[self.class allocWithZone:zone] init];
    copyedModel->_name = self.name;
    copyedModel->_age = self.age;
    return copyedModel;
}

@end

使用

    MyModel * model = [[MyModel alloc] init];
    model.name = @"wenchen";
    model.age = 24;
    MyModel * copyedModel = [model copy];

然后在LLDB中可以查看对象地址,可以看到是两个独立的对象

(lldb) po copyedModel
<MyModel: 0x7f958971b690>

(lldb) po model
<MyModel: 0x7f958971b5b0>

Swift

class MyModel:NSObject,NSCopying{ func copyWithZone(zone: NSZone) -> AnyObject { let copyedModel = self.dynamicType() return copyedModel } required override init() { } 

简单测试

 let model1 = MyModel()
 let model2 = model1.copy()
(lldb) po model1
<SWTest.MyModel: 0x7fafe0476f40>

(lldb) po model2
<SWTest.MyModel: 0x7fafe0476ec0>

这里顺便提一下,如何在Swift中声明一个OC中的copy 属性

 @NSCopying var name:NSString?

使用关键字 @NSCopying

你可能感兴趣的:(ios,Model,协议,NSCopying)