在某些情况下(例如,当连接到内部进行测试时),能够创建不采用NSCopying
(不实现-copyWithZone:
)的类实例的副本会很方便。如何做到这一点?(注意:在一个类别中实现协议是不够的,因为并非所有类的实例变量都在其标题中可见。)
我已经尝试迭代对象的Ivar
s,并且(1)对于递归(或保留)的对象类型,以及(2)对于原始类型,获取原始实例中 ivar 的地址以及正在制作的副本和memcpy
ing缓冲区从源 ivar 的地址开始到目标 ivar 的地址。
@interface NSObject (ADDLCopy)
- (id)addl_generateCopyDeep:(BOOL)deepCopy;
@end
@implementation NSObject (ADDLCopy)
//modified from http://stackoverflow.com/a/12265664/1052673
- (void *)addl_ivarPointerForName:(const char *)name
{
void *res = NULL;
Ivar ivar = class_getInstanceVariable(self.class, name);
if (ivar) {
res = (void *)self + ivar_getOffset(ivar);
}
return res;
}
- (id)addl_generateCopyDeep:(BOOL)deepCopy;
{
id res = [[self.class alloc] init];
unsigned int count = 0;
Ivar *ivars = class_copyIvarList(self.class, &count);
for (unsigned int i = 0; i < count; i++) {
Ivar ivar = ivars[i];
//We need to try here because of a bug with NSGetSizeAndAlignment
//which prevents bitfields from being handled properly and results
//in an exception being thrown. See this link for more discussion:
//http://lists.apple.com/archives/cocoa-dev/2008/Sep/msg00883.html
@try {
NSUInteger size = 0;
const char *encoding = ivar_getTypeEncoding(ivar);
NSGetSizeAndAlignment(encoding, &size, NULL);
char firstEncodingCharacter[2];
strncpy(firstEncodingCharacter, encoding, 1);
firstEncodingCharacter[1] = 0;
if (strcmp(firstEncodingCharacter, "@") == 0) {
if (deepCopy) {
id original = object_getIvar(self, ivar);
id copy = [original addl_generateCopyDeep:deepCopy];
object_setIvar(res, ivar, copy);
} else {
id original = object_getIvar(self, ivar);
object_setIvar(res, ivar, original);
}
} else {
const char *name = ivar_getName(ivar);
void *bytesSource = [self addl_ivarPointerForName:name];
void *bytesTarget = [res addl_ivarPointerForName:name];
memcpy(bytesTarget, bytesSource, size);
}
}
@catch (NSException *exception) {}
@finally {}
}
free(ivars);
return res;
}
@end
这有点工作,但我知道有几个明显的问题,更不用说那些我不知道的问题。首先,它不会复制从超类继承的 ivars。其次,它不适用于收藏。此外,由于 中的一个错误NSGetSizeAndAlignment
,它不适用于位掩码。此外,它没有考虑关联的对象。
如何递归复制对象的实例(以及它拥有的所有对象)?如果这不是完全可能的(处理保留并存储在 void 指针中的拥有对象即使可能的话似乎也相当困难),它可以做到什么程度?