首页 > 代码库 > IOS_反射

IOS_反射

////  PJReflect.m//  新浪微博////  Created by pj on 14-8-8.//  Copyright (c) 2014年 pj. All rights reserved.//#import "PJReflect.h"#import "PJFiled.h"#import <objc/runtime.h>#import <Foundation/NSObjCRuntime.h>@implementation PJReflect+ (NSArray*)getFiled:(id)p{    NSMutableArray *arryFiled = [NSMutableArray array];    Class cls = [p class];    unsigned int ivarsCnt = 0;    // 获取类成员变量列表,ivarsCnt为类成员数量    Ivar *ivars = class_copyIvarList(cls, &ivarsCnt);    // 遍历成员变量列表,其中每个变量都是Ivar类型的结构体    for (const Ivar *p = ivars; p < ivars + ivarsCnt; ++p)    {        PJFiled *pFiled = [[PJFiled alloc] init];        Ivar const ivar = *p;        NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];        pFiled.argName = key;        NSString *type = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];        pFiled.type = type;        [arryFiled addObject:pFiled];    }    return arryFiled;}+ (id)reflex:(NSDictionary *)dict object:(id)object{    if (![dict isKindOfClass:[NSDictionary class]]) {        // 不是集合        return nil;    }    // 1.先循环变量    NSArray* array = [self getFiled:object];    // 然后开始遍历    // 先遍历dict??还是先遍历我们的对象呢??遍历对象把    for (int i = 0; i < array.count; i++) {        PJFiled *f = array[i];        if (f.isBase == NO) {            // 赋值            if (nil == dict[f.argName]) {                continue;            }            [object setValue:dict[f.argName] forKey:f.argName];        }else        {            id obj = [NSClassFromString(f.type) alloc];            if (dict[f.argName] == nil) {                continue;            }            [object setValue:obj forKey:f.argName];            [self reflex:dict[f.argName] object:obj];        }    }    return object;}@end////  PJFiled.h//  反射1////  Created by pj on 14-8-8.//  Copyright (c) 2014年 pj. All rights reserved.//#import <Foundation/Foundation.h>@interface PJFiled : NSObject@property (copy,nonatomic) NSString *argName; // 变量名@property (copy,nonatomic) NSString *type; // 变量类型@property (assign,nonatomic) BOOL isBase; // 是否是基类@end////  PJFiled.m//  反射1////  Created by pj on 14-8-8.//  Copyright (c) 2014年 pj. All rights reserved.//#import "PJFiled.h"@implementation PJFiled- (void)setType:(NSString *)type{   // @"User"  // 取中间        NSRange rang = NSMakeRange(2,[type length] - 3);    type = [type substringWithRange:rang];    if ([type hasPrefix:@"NS"]) {        self.isBase = false;    }else    {        if (NSClassFromString(type) != nil) {            self.isBase = true;        }else        {            self.isBase = false;        }    }    _type = type;}- (void)setArgName:(NSString *)argName{    if ([argName hasPrefix:@"_"]) {        // 删除_        argName = [argName substringFromIndex:1];    }    _argName = argName;}@end