本文当中,利用oc的运行时机制,重写- (NSString *)description(类似于java的toString方法)来达到输出内容的目的。废话不多说,看代码
- (NSString *)description { NSMutableString *stringM = [NSMutableString stringWithFormat:@" <%@: %p> ",self.class,self]; //获取本类的clas Class cls = object_getClass(self); //输出参数,获取本类(不包括父类)成员变量总数 unsigned int outCount = 0; //遍历本身和父类,并排除NSObject while (cls != NULL && cls != NSClassFromString(@"NSObject")) { //返回成员变量的的指针数组 Ivar *ivars = class_copyIvarList(cls, &outCount); for (int i = 0; i < outCount; i++) { //拿到成员变量结构体指针 Ivar ivar = ivars[i]; //获得成员变量的名字 NSString *ivarNameKey = [NSString stringWithUTF8String:ivar_getName(ivar)]; //删除下划线(因为编译器自动为属性生成带_的成员变量) if ([ivarNameKey hasPrefix:@"_"]) { ivarNameKey = [ivarNameKey stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:@""]; } //获取变量的值 id value = [self valueForKey:ivarNameKey]; [stringM appendString:[NSString stringWithFormat:@" %@ -> %@ ",ivarNameKey,value]]; } //释放指针 free(ivars); //去父类中找 cls = class_getSuperclass(cls); } return stringM; }