zoukankan      html  css  js  c++  java
  • runtime使用技巧一

    runtime运行时:

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

    runtime反射属性列表:

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

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

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

    -(void)printAll:(id)obj{
        NSString * str = nil;
        str = [NSString stringWithFormat:@"
    %@:
    ",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:@"%@ 
     %@%@:%@",str,nullStr,key,[self printStr:value Num:key.length + num +1]];
        }
        str = [NSString stringWithFormat:@"%@ 
     %@}",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:喝水了

                   } 

           } 

     }

  • 相关阅读:
    数据集冲突
    苹果如何设计iPad的商业模式
    IT部门应如何制定技术路线图
    关于软件测试
    c#写文件
    正则表达式语法及常用表达式。
    使用Mysql的Replication功能实现数据库同步
    CMMI=大象关冰箱?
    asp.net 中RegularExpressionValidator的bug|IE的bug?
    Singleton 模式的Java和C#的实现方法
  • 原文地址:https://www.cnblogs.com/ggxbq/p/3712143.html
Copyright © 2011-2022 走看看