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

https://www.jianshu.com/p/16df592f60a6

开发中会遇到将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);
}



 

猜你喜欢

转载自blog.csdn.net/georgehenrywilliam/article/details/88367775