首先導(dǎo)入運行時
#import <objc/runtime.h>
然后實現(xiàn)如下方法:
- (id)copyWithZone:(NSZone *)zone
{
??? XLCommentModel *cModel = class_createInstance([XLCommentModel class], 0);
???
??? // 成員變量的數(shù)量
??? unsigned int outCount = 0;
???
??? // 獲得所有的成員變量
??? Ivar *ivars = class_copyIvarList([XLCommentModel class], &outCount);
???
??? // 遍歷所有的成員變量
??? for (int i = 0; i<outCount; i++) {
??????? // 取出i位置對應(yīng)的成員變量
??????? Ivar oldIvar = ivars[i];
???????
??????? //成員變量名
??????? NSString *key = [NSString stringWithCString:ivar_getName(oldIvar) encoding:NSUTF8StringEncoding];
??????? //成員變量值
??????? id value = [self valueForKey:key];
??????? //復(fù)制成員變量值
??????? [cModel setValue:value forKey:key];
???????
??????? // 獲得成員變量的名字
//??????? NSLog(@"變量名:%s 變量類型:%s", ivar_getName(oldIvar),ivar_getTypeEncoding(oldIvar));
??? }
???
??? // 如果函數(shù)名中包含了copy\new\retain\create等字眼,那么這個函數(shù)返回的數(shù)據(jù)就需要手動釋放
??? free(ivars);
???
??? return cModel;
}