通过runtime打印出对象所有属性的值

今天给给大家提供的关于NSObject的category,通过runtime打印属性的值,相当有用哦,以后你再也不用每个对象都通过NSLog来逐个打印属性值了。

源码:

NSObject+Properties.h 与 NSObject+Properties.m

//
// NSObject+Properties.h
//
// Created by YouXianMing on 14-9-4.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
// #import <Foundation/Foundation.h> @interface NSObject (Properties) - (NSDictionary*)propertiesValues; @end
//
// NSObject+Properties.m
//
// Created by YouXianMing on 14-9-4.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
// #import "NSObject+Properties.h"
#import <objc/runtime.h> @implementation NSObject (Properties) - (NSDictionary*)propertiesValues
{
// 获取属性列表
NSArray *properties = [self propertyNames:[self class]]; // 根据属性列表获取属性值
return [self propertiesAndValuesDictionary:self properties:properties];
} #pragma private - 私有方法 // 获取一个类的属性名字列表
- (NSArray*)propertyNames:(Class)class
{
NSMutableArray *propertyNames = [[NSMutableArray alloc] init];
unsigned int propertyCount = ;
objc_property_t *properties = class_copyPropertyList(class, &propertyCount); for (unsigned int i = ; i < propertyCount; ++i)
{
objc_property_t property = properties[i];
const char *name = property_getName(property); [propertyNames addObject:[NSString stringWithUTF8String:name]];
} free(properties); return propertyNames;
} // 根据属性数组获取该属性的值
- (NSDictionary*)propertiesAndValuesDictionary:(id)obj properties:(NSArray *)properties
{
NSMutableDictionary *propertiesValuesDic = [NSMutableDictionary dictionary]; for (NSString *property in properties)
{
SEL getSel = NSSelectorFromString(property); if ([obj respondsToSelector:getSel])
{
NSMethodSignature *signature = nil;
signature = [obj methodSignatureForSelector:getSel];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:obj];
[invocation setSelector:getSel];
NSObject * __unsafe_unretained valueObj = nil;
[invocation invoke];
[invocation getReturnValue:&valueObj]; //assign to @"" string
if (valueObj == nil)
{
valueObj = @"";
} propertiesValuesDic[property] = valueObj;
}
} return propertiesValuesDic;
} @end
//
// NSObject+Properties.m
//
// Created by YouXianMing on 14-9-4.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
// #import "NSObject+Properties.h"
#import <objc/runtime.h> @implementation NSObject (Properties) - (NSDictionary*)propertiesValues
{
// 获取属性列表
NSArray *properties = [self propertyNames:[self class]]; // 根据属性列表获取属性值
return [self propertiesAndValuesDictionary:self properties:properties];
} #pragma private - 私有方法 // 获取一个类的属性名字列表
- (NSArray*)propertyNames:(Class)class
{
NSMutableArray *propertyNames = [[NSMutableArray alloc] init];
unsigned int propertyCount = ;
objc_property_t *properties = class_copyPropertyList(class, &propertyCount); for (unsigned int i = ; i < propertyCount; ++i)
{
objc_property_t property = properties[i];
const char *name = property_getName(property); [propertyNames addObject:[NSString stringWithUTF8String:name]];
} free(properties); return propertyNames;
} // 根据属性数组获取该属性的值
- (NSDictionary*)propertiesAndValuesDictionary:(id)obj properties:(NSArray *)properties
{
NSMutableDictionary *propertiesValuesDic = [NSMutableDictionary dictionary]; for (NSString *property in properties)
{
SEL getSel = NSSelectorFromString(property); if ([obj respondsToSelector:getSel])
{
NSMethodSignature *signature = nil;
signature = [obj methodSignatureForSelector:getSel];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:obj];
[invocation setSelector:getSel];
NSObject * __unsafe_unretained valueObj = nil;
[invocation invoke];
[invocation getReturnValue:&valueObj]; //assign to @"" string
if (valueObj == nil)
{
valueObj = @"";
} propertiesValuesDic[property] = valueObj;
}
} return propertiesValuesDic;
} @end

使用详情:

测试用Model

//
// YXModel.h
// Test
//
// Created by YouXianMing on 14-9-4.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
// #import <Foundation/Foundation.h> @interface YXModel : NSObject @property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSNumber *age;
@property (nonatomic, strong) NSString *sex;
@property (nonatomic, strong) NSDictionary *info; @end
//
// YXModel.m
// Test
//
// Created by YouXianMing on 14-9-4.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
// #import "YXModel.h" @implementation YXModel @end

使用:

//
// AppDelegate.m
// Test
//
// Created by YouXianMing on 14-9-4.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
// #import "AppDelegate.h"
#import "NSObject+Properties.h"
#import "YXModel.h" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// 初始化model
YXModel *model = [YXModel new]; // 赋值
model.name = @"YouXianMing";
model.age = @;
model.sex = @"male";
model.info = @{@"A":@"B", @"C":@"D"}; // 打印出所有属性的值
NSLog(@"%@", model.propertiesValues); return YES;
} @end

打印信息:

2014-09-04 19:39:08.913 Test[1278:60b] {

age = 26;

info =     {

A = B;

C = D;

};

name = YouXianMing;

sex = male;

}

通过runtime打印出对象所有属性的值的更多相关文章

  1. C#通过反射获得对象所有属性和值

    C#获得对象的所有属性和值 public void GetPros() { UserInfo userInfo = new UserInfo(); userInfo.ID = ; userInfo.N ...

  2. python求平均数及打印出低于平均数的值列表

    刚学Python的时候还是要多动手进行一些小程序的编写,要持续不断的进行,知识才能掌握的牢.今天就讲一下Python怎么求平均数,及打印出低于平均数的数值列表 方法一: scores1 =  [91, ...

  3. js打印出对象的方法

    var description = ""; for (var i in order) { var property = order[i]; description += i + & ...

  4. javascript对比两个数组,打印出差异值

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  5. java算法面试题:有一个字符串,其中包含中文字符、英文字符和数字字符,请统计和打印出各个字符的个数 按值的降序排序,如果值相同则按键值的字母顺序

    package com.swift; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; publi ...

  6. scala基础题--函数可以没有返回值案例,编写一个函数,从终端输入一个整数,打印出对应的金字塔

    函数可以没有返回值案例,编写一个函数,从终端输入一个整数,打印出对应的金字塔 import scala.io.StdIn object work02 { def main(args: Array[St ...

  7. [JavaScript] console.log只在查看时才会读取这个打印的对象,并把此刻相关属性和值显示出来

      /** * 写个函数解决console.log只在查看时才会读取这个打印的对象,并把此刻相关属性和值显示出来 * @param arg */ const log = function (...ar ...

  8. java例题_47 读取 7 个数(1—50)的整数值,每读取一个值,程序打印出该值个数的*

    1 /*47 [程序 47 打印星号] 2 题目:读取 7 个数(1-50)的整数值,每读取一个值,程序打印出该值个数的*. 3 */ 4 5 /*分析 6 * 1.多次读取---for循环 7 * ...

  9. 福利->KVC+Runtime获取类/对象的属性/成员变量/方法/协议并实现字典转模型

    我们知道,KVC+Runtime可以做非常多的事情.有了这个,我们可以实现很多的效果. 这里来个福利,利用KVC+Runtime获取类/对象的所有成员变量.属性.方法及协议: 并利用它来实现字典转模型 ...

随机推荐

  1. Tomcat中组件的生命周期管理公共接口Lifecycle

    Tomcat的组件都会实现一个Lifecycle接口,以方便组件的生命周期的统一管理 interface Lifecycle 组件生命周期中主要的几个方法 增加监听器,事件委托机制 public vo ...

  2. logback 日志打印输出

    slf4j 其实是一个日志的抽象层, 其本质仍然需要真正的实现 他可以解决代码中独立于任意特定的日志类库, 可以减少很多维护日志的麻烦, 除此之外, 还有占位符的特性, {}, 类似于String#f ...

  3. Cacheable redis 宕机

    使用Cacheable注解Redis方法时,如果Redis服务器挂了,就直接抛出异常了, java.net.ConnectException: Connection refused: connect ...

  4. ADB故障时的一些命令

    开发中经常用到adb重启等操作,简单记录一下. 1.重启 adb kill-server adb start-server 2.显示版本号 adb version 3.显示已连接的设备 adb dev ...

  5. 基于json-lib-2.2.2-jdk15.jar的JSON解析工具类大集合

    json解析之前的必备工作:导入json解析必须的六个包 资源链接:百度云:链接:https://pan.baidu.com/s/1dAEQQy 密码:1v1z 代码示例: package com.s ...

  6. c# 键值对照表

    虚拟键值表 虚拟键 十六进制值 十进制值 相应键盘或鼠标键 VK_LBUTTON 1 1 鼠标左键 VK_RBUTTON 2 2 鼠标右键 VK_CANCEL 3 3 Ctrl-Break键 VK_M ...

  7. MVC 之HTML辅助方法

    顾名思义,HTML辅助方法(HTML Helper)就是用来辅助产生HTML之用,在开发View的时候一定会面对许多HTML标签,处理这些HTML的工作非常繁琐,为了降低View的复杂度,可以使用HT ...

  8. 【 js 片段 】移动端适配简易步骤

    手机端全部适配简易步骤,不确保没有bug. 1.HTML 的 head 部分中加入如下代码: <meta name="viewport" content="widt ...

  9. [js常用]百度将文字转化为语音实例

    嗷嗷方便的文字转语音,不过用的时候记得到百度语音上申请key,免费的.之前在网络上看到有人写了一部分,自己丰富下,以后用也方便 <!DOCTYPE html PUBLIC "-//W3 ...

  10. python中新式类和经典类

    python中的类分为新式类和经典类,具体有什么区别呢?简单的说, 1.新式类都从object继承,经典类不需要. Python 2.x中默认都是经典类,只有显式继承了object才是新式类 Pyth ...