description方法是可以開發(fā)者自定義的,返回該對象實例的描述棘幸,但去重寫每一個類的description方法太繁瑣了,于是我就自己實現(xiàn)了一個BaseModel作為所有model的基類倦零,利用runtime動態(tài)的獲取當前實例的所有屬性名稱和值够话,
/*
*利用runtime打印所有的屬性名稱和值
*/
- (NSString *)description{
NSString *descriptionString = NSStringFromClass([self class]);
Class tempClass = [self class];
//循環(huán)執(zhí)行 直到父類循環(huán)到 NSObject 為止
while (tempClass != [NSObject class]) {
unsigned int count = 0 ;
//獲取屬性列表
objc_property_t *propertyList = class_copyPropertyList(tempClass, &count);
for (int i = 0; i < count; i ++) {
//取出屬性名和值 拼接字符串。
objc_property_t property = propertyList[i];
NSString *propertyName = [NSString stringWithUTF8String: property_getName(property)];
NSString *propertyValue = [self valueForKey:propertyName];
NSString *keyValueDic = [NSString stringWithFormat:@" %@--%@, ",propertyName,propertyValue];
descriptionString = [descriptionString stringByAppendingString:keyValueDic];
}
free(propertyList);
//釋放指針
tempClass = [tempClass superclass];
//指向父類
}
return descriptionString;
}
這里說一下循環(huán)遍歷父類的屬性列表的原因光绕,如果只是遍歷當前Class對象的屬性列表女嘲,只能顯示出當前類添加的屬性,并不能體現(xiàn)出類本身的所有屬性诞帐。到NSObject對象為止欣尼,因為到NSObject這一層,我們把我們自己定義的所有屬性都拿到了停蕉,算是一個截止點愕鼓。