轉作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
}
}
}