转作ios开发有一段时间了,但一直没有时间整理知识,今天开始分享本身的一些心得,主要为了交流学习,错误的地方但愿你们多多指正,共同进步,好的下面进入正题。runtime不少人必定不陌生(陌生的话,你们能够选学习一下,网上有不少大神已经给出了),但咱们作到学以至用了么?下面我来分享一点我在runtime中使用的一点心得,但愿对你们有所帮助。ios
经过runtime能够反射取到咱们运行时类的属性列表。这个其实对咱们开发是很是有帮助的。学习
今天来说它的一种使用方法:spa
MVC模式中,咱们封装的模型中会包含大量的实体,属性。而咱们在开发的时候常常遇到传递model的状况,为了开发方便,须要查看model中各个属性的值。而runtime就帮咱们很好的解决了这个问题。废话很少说了,直接上代码。code
-(void)printAll:(id)obj{ NSString * str = nil; str = [NSString stringWithFormat:@"\n%@:\n",object_getClass(obj)]; str = [str stringByAppendingString:[self printStr:obj Num:0]]; str = [NSString stringWithFormat:@"%@",str]; NSLog(@"%@",str); } -(NSString *)printStr:(id)obj Num:(NSInteger)num{ unsigned int outCount, i; objc_property_t *properties = class_copyPropertyList([obj class], &outCount); if (outCount == 0) { return [NSString stringWithFormat:@"%@",obj]; } NSString * str = nil; NSString * nullStr = [self printNullStr:num]; str = @"{"; for (i=0; i<outCount; i++) { objc_property_t property = properties[i]; NSString * key = [[NSString alloc]initWithCString:property_getName(property) encoding:NSUTF8StringEncoding]; id value = [obj valueForKey:key]; str = [NSString stringWithFormat:@"%@ \n %@%@:%@",str,nullStr,key,[self printStr:value Num:key.length + num +1]]; } str = [NSString stringWithFormat:@"%@ \n %@}",str,nullStr]; return str; } -(NSString *)printNullStr:(NSInteger)num{ NSString * str = @""; for (int i = 0 ; i<num; i++) { str = [str stringByAppendingString:@" "]; } return str; }
记得须要申明头文件orm
#import <objc/runtime.h>对象
将上面的方法 添加到NSObject的类别当中,在.pch中申明为全局的blog
这样任何一个id对象就均可以调用printAll方法来输出打印了开发
效果以下:get
014-05-06 17:38:58.013 LTTest[10011:90b] string
MyTestModle:
{
name:吃饭了
address:喝水了
model:{
name:吃饭了2
address:2
mymodel:{
name:吃饭了3
address:喝水了3
}
}
}