iOS runtime实现自定义model的copy赋值

开发中会遇到将A的model传递到下一个B;
如果直接

B.model = model;

这样的话,A 和B的model是同一块内存,导致当在B修改了model后,A的model也随之改变。

解决方案一:

1、在传值的地方这样写

2、然后需要让model遵守NSCopying,NSMutableCopying协议(不然会崩溃),重写copyWithZone和mutableCopyWithZone方法。

下面代码不太明白的话可以看这篇Runtime应用场景总结
##下面代码你只需要更换下model的类型,可直接复用。(在使用的地方需要导入#import <objc/message.h>)
-(id)copyWithZone:(NSZone *)zone{
    HuForumCellModel *model = [[HuForumCellModel allocWithZone:zone] init];
    unsigned int count = 0;
    objc_property_t *properties = class_copyPropertyList([self class], &count);
    for (int i = 0; i<count; i++) {
        objc_property_t property = properties[i];
        const char *name = property_getName(property);
        NSString *propertyName = [NSString stringWithUTF8String:name];
        id value = [self valueForKey:propertyName];
        if (value) {
            [model setValue:value forKey:propertyName];
        }
    }
    free(properties);
    return model;
}

-(id)mutableCopyWithZone:(NSZone *)zone{
    HuForumCellModel *model = [[HuForumCellModel allocWithZone:zone] init];
    unsigned int count = 0;
    objc_property_t *properties = class_copyPropertyList([self class], &count);
    for (int i = 0; i<count; i++) {
        objc_property_t property = properties[i];
        const char *name = property_getName(property);
        NSString *propertyName = [NSString stringWithUTF8String:name];
        id value = [self valueForKey:propertyName];
        if (value) {
            [model setValue:value forKey:propertyName];
        }
    }
    free(properties);
    return model;
}

方案二:
不需要在赋值的地方用copy,而是在接收的地方,重写setModel方法。

-(void)setModel:(HuForumCellModel *)model{
    _model = [[HuForumCellModel alloc] init];
##不能用下面这一局,不然地址又变成和model的地址一样了
//    _model = model;
    unsigned int count = 0;
    objc_property_t *properties = class_copyPropertyList([HuForumCellModel class], &count);
    for (int i = 0; i < count; i++) {
        const char *name = property_getName(properties[i]);
        NSString *propertyName = [NSString stringWithUTF8String:name];
        id propertyValue = [model valueForKey:propertyName];
        if (propertyValue) {
            [_model setValue:propertyValue forKey:propertyName];
        }
    }
    free(properties);
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,963评论 1赞 32
  • 一、从面向对象到Objective-C概览copy 1、面向对象: In object-oriented prog...
    adrian920阅读 873评论 0赞 3
  • 本文为转载: 作者:zyydeveloper 链接:http://www.jianshu.com/p/5f776a...
    Buddha_like阅读 1,111评论 0赞 2
  • 本文相关代码 一、从面向对象到Objective-C概览copy 1、面向对象: In object-orient...
    雷鸣1010阅读 515评论 0赞 0
  • 微甜店位于桐乡路与繁华的步行街相交叉的路口处,所以生意还是挺不错的。店门口的落地窗里透出各种诱人的甜品,吸引着人忍...
    a小蛟阅读 446评论 0赞 0

友情链接更多精彩内容