首页 > 学院 > 开发设计 > 正文

runtime使用技巧一

2019-11-14 20:30:38
字体:
来源:转载
供稿:网友

runtime运行时:

  转做ios开发有一段时间了,但一直没有时间整理知识,今天开始分享自己的一些心得,主要为了交流学习,错误的地方希望大家多多指正,共同进步,好的下面进入正题。runtime很多人一定不陌生(陌生的话,大家可以选学习一下,网上有很多大神已经给出了),但我们做到学以致用了么?下面我来分享一点我在runtime中使用的一点心得,希望对大家有所帮助。

runtime反射属性列表:

通过runtime可以反射取到我们运行时类的属性列表。这个其实对我们开发是非常有帮助的。

今天来讲它的一种使用方法:

MVC模式中,我们封装的模型中会包含大量的实体,属性。而我们在开发的时候经常遇到传递model的情况,为了开发方便,需要查看model中各个属性的值。而runtime就帮我们很好的解决了这个问题。废话不多说了,直接上代码。

-(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;}

记得需要申明头文件

#import <objc/runtime.h>

将上面的方法 添加到NSObject的类别当中,在.pch中申明为全局的

这样任何一个id对象就都可以调用printAll方法来输出打印了

效果如下:

014-05-06 17:38:58.013 LTTest[10011:90b] 

MyTestModle:

 name:吃饭了 

 address:喝水了 

 model:{ 

       name:吃饭了

       address:2 

       mymodel:{ 

               name:吃饭了

               address:喝水了

               } 

       } 

 }

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表