最近項(xiàng)目中有一個(gè)評(píng)價(jià)功能,但是遇到了一個(gè)問題, 創(chuàng)建不同的數(shù)組從數(shù)據(jù)源中取出標(biāo)簽數(shù)據(jù),再次存儲(chǔ),發(fā)現(xiàn)數(shù)據(jù)修改后,源數(shù)據(jù)也有修改,查閱多方資料,是深淺拷貝的問題,雖然多次修改,存儲(chǔ)。new。init ,但是數(shù)組中存儲(chǔ)的數(shù)據(jù)仍然指向源數(shù)組所在內(nèi)存地址 在此作出記錄
實(shí)現(xiàn)NSObject+Coding方法

NSObject+Coding.h
/**
* 快速實(shí)現(xiàn)NSCoding協(xié)議中,編碼和解碼的方法
*/
@interface NSObject (Coding)
/**
* 通過Runtime解碼
*
* @param decoder NSCoder對(duì)象
*/
- (void)lxz_decodeWithCoder:(NSCoder *)decoder;
/**
* 通過Runtime編碼
*
* @param coder NSCoder對(duì)象
*/
- (void)lxz_encodeWithCoder:(NSCoder *)coder;
/**
* 通過Runtime實(shí)現(xiàn)自動(dòng)copy
*
* @param zone NSZone對(duì)象
* @return 新對(duì)象
*/
- (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;
}
下載鏈接:https://download.csdn.net/download/qq_32782323/10504563