yj.iOS 多标签点赞评论评价功能

最近项目中有一个评价功能,但是遇到了一个问题, 创建不同的数组从数据源中取出标签数据,再次存储,发现数据修改后,源数据也有修改,查阅多方资料,是深浅拷贝的问题,虽然多次修改,存储。new。init ,但是数组中存储的数据仍然指向源数组所在内存地址 在此作出记录

实现NSObject+Coding方法

NSObject+Coding

NSObject+Coding.h

/**

* 快速实现NSCoding协议中,编码和解码的方法

*/

@interface NSObject (Coding)

/**

* 通过Runtime解码

*

* @param decoder NSCoder对象

*/

- (void)lxz_decodeWithCoder:(NSCoder *)decoder;

/**

* 通过Runtime编码

*

* @param coder NSCoder对象

*/

- (void)lxz_encodeWithCoder:(NSCoder *)coder;

/**

* 通过Runtime实现自动copy

*

* @param zone NSZone对象

* @return 新对象

*/

- (id)lxz_copyWithZone:(NSZone *)zone;

NSObject+Coding.m

 

@implementation NSObject (Coding)

- (void)lxz_decodeWithCoder:(NSCoder *)decoder {

    unsigned int count = 0;

    Ivar *ivars = class_copyIvarList([self class], &count);

    if (ivars) {

        for (int i = 0; i < count; i++) {

            Ivar ivar = ivars[i];

            const char *ivarName = ivar_getName(ivar);

            NSString *keyName = [[NSString alloc] initWithUTF8String:ivarName];

            id value = [decoder decodeObjectForKey:keyName];

            [self setValue:value forKeyPath:keyName];

        }

    }

    free(ivars);

}

- (void)lxz_encodeWithCoder:(NSCoder *)coder {

    unsigned int count = 0;

    Ivar *ivars = class_copyIvarList([self class], &count);

    if (ivars) {

        for (int i = 0; i < count; i++) {

            Ivar ivar = ivars[i];

            const char *ivarName = ivar_getName(ivar);

            NSString *keyName = [[NSString alloc] initWithUTF8String:ivarName];

            id value = [self valueForKeyPath:keyName];

            [coder encodeObject:value forKey:keyName];

        }

    }

    free(ivars);

}

- (id)lxz_copyWithZone:(NSZone *)zone {

    NSObject *obj = [[[self class] allocWithZone:zone] init];

    unsigned int count = 0;

    Ivar *ivars = class_copyIvarList([self class], &count);

    if (ivars) {

        for (int i = 0; i < count; i++) {

            Ivar ivar = ivars[i];

            const char *ivarName = ivar_getName(ivar);

            NSString *keyName = [[NSString alloc] initWithUTF8String:ivarName];

            id value = [self valueForKeyPath:keyName];

 

            if ([value respondsToSelector:@selector(copyWithZone:)]) {

                [obj setValue:[value copy] forKey:keyName];

            } else {

                [obj setValue:value forKey:keyName];

            }

        }

    }

    free(ivars);

    return obj;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值