iOS 开发学习39 简单学习反射的部分用法

内省

在程序运行时获取对象的类型。

遍历属性

    unsigned int outCount,i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    NSMutableArray *keys = [[NSMutableArray alloc] initWithCapacity:outCount];
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        [keys addObject:propertyName];
    }

    free(properties);

给对象自动赋值的代码

- (NSArray*)propertyKeys
{
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    NSMutableArray *keys = [[NSMutableArray alloc] initWithCapacity:outCount];
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        [keys addObject:propertyName];
    }
    free(properties);
    return keys;
}


- (BOOL)reflectDataFromOtherObject:(NSObject*)dataSource
{
    BOOL ret = NO;
    for (NSString *key in [self propertyKeys]) {
        if ([dataSource isKindOfClass:[NSDictionary class]]) {
            ret = ([dataSource valueForKey:key]==nil)?NO:YES;
        }
        else
        {
            ret = [dataSource respondsToSelector:NSSelectorFromString(key)];
        }
        if (ret) {
            id propertyValue = [dataSource valueForKey:key];
            //该值不为NSNULL,并且也不为nil
            if (![propertyValue isKindOfClass:[NSNull class]] && propertyValue!=nil) {
                [self setValue:propertyValue forKey:key];
            }            
        }
    }
    return ret;
}

/////使用方法
NSDictionary *dicJsonData;
EntityObject *objValue;
[objValue reflectDataFromOtherObject:dicJsonData];//这样就可以完成对象的自动赋值了,

根据类的名称创建实例

 Class classname=NSClassFromString(@"ClassName");
 id obj=[[classname alloc]init];
 //调用方法
 SEL selector = NSSelectorFromString(@"CallFunc");
 [obj  performSelector:selector withObject:nil];

获取方法的指针

IMP test = [self methodForSelector:@selector(start)];
test();

判断是否是类或子类的实例

 -(BOOL)isKindOfClass:classObj

判断是否是这个类的实例

 -(BOOL)isMemberOfClass:classObj

判断是否响应指定消息

原型:
-(BOOL)respondsToSelector:(SEL)aSelector
示例:
if ([self respondsToSelector:@selector(test)]) {
    NSLog(@"YES");
} else {
    NSLog(@"NO");
}

判断是否符合指定协议

原型:
-(BOOL)conformsToProtocol:(Protocal *)aProtocal
示例:
if ([self conformsToProtocol:@protocol(NSObject)]) {
    NSLog(@"YES");
} else {
    NSLog(@"NO");
}

获取类名

NSString *className = NSStringFromClass([theObject class]);

你可能感兴趣的:(ios)