一个 reignited NSObject 的扩展,允许运行时检查。它允许您生成具有对象的属性键值对的字典。
#import "NSObject+introspection.h"
。由于 NSObject 是几乎所有 Objective-C 对象的根类,因此几乎任何类都可以调用它。
它公开了 4 个方法
-(NSDictionary*)propertiesDict; //returns a dictionary with key-value pairs of the objects declared properties
-(NSDictionary *)iVarsDict; //returns a dictionary with key-value pairs of the objects iVars
-(NSDictionary *)methodsDict; //returns a dictionary with key-value pairs of the objects methods
//currently the key and value are both the method name string
-(NSDictionary *)objectIntrospectDictionary; //returns a dictionary with the above 3 dictionaries with keys "properties", "iVars" and "methods"
nil
的属性或 iVar,它对应的键将是 [NSNull null]
值。SomeObject.h
//SomeObject.h
#import <Foundation/Foundation.h>
#import "SomeOtherObject.h" // not described in readme
@interface SomeObject : NSObject {
NSString *anIvarString;
}
@property (nonatomic, strong) NSString *someString;
@property (nonatomic, strong) SomeOtherObject *someOtherObject;
SomeObject.m
//SomeObject.m
#import "SomeObject.h"
@implementation SomeObject
@synthesize someString;
@synthesize someOtherObject;
-(id)init{
self=[super init];
if(self){
anIvarString=@"some string value";
self.someString=@"a string which is a property of our object"
self.someOtherObject=[[SomeOtherObject alloc] init];
}
return self;
}
代码中任何地方
#import "NSObject+Introspection.h"
#import "SomeObject.h"
...
SomeObject *someObject=[[SomeObject alloc] init];
NSDictionary *propsDict=[someObject propertiesDict];
NSLog (@"%@",propsDict.description);
日志输出
{
someOtherObject = "<someOtherObject: 0x765fe50>"; //the dictionary contains the actual object instance
someString = "a string which is a property of our object";
}