runtime动态添加属性

来源:互联网 发布:python 2.7安装 编辑:程序博客网 时间:2024/03/29 18:38
使用运行时库,必须要先引入 objc/runtime.h

看一个类别和动态添加属性的例子


UILabel+Associate.h#import <UIKit/UIKit.h>@interface UILabel (Associate)- (void) setFlashColor:(UIColor *) flashColor;- (UIColor *) getFlashColor;@end


UILabel+Associate.m#import "UILabel+Associate.h"#import <objc/runtime.h>    @implementation UILabel (Associate)    static char flashColorKey;    - (void) setFlashColor:(UIColor *) flashColor{      objc_setAssociatedObject(self, &flashColorKey, flashColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);  }    - (UIColor *) getFlashColor{     return objc_getAssociatedObject(self, &flashColorKey);  }    @end  

调用代码:UILabel *lab = [[UILabel alloc] init];      [lab setFlashColor:[UIColor redColor]];      NSLog(@"%@", [lab getFlashColor]); 


判断一个类里是否包含某个属性

+ (BOOL) getVariableWithClass:(Class) myClass varName:(NSString *)name{    unsigned int outCount, i;    Ivar *ivars = class_copyIvarList(myClass, &outCount);    for (i = 0; i < outCount; i++) {        Ivar property = ivars[i];        NSString *keyName = [NSString stringWithCString:ivar_getName(property) encoding:NSUTF8StringEncoding];        keyName = [keyName stringByReplacingOccurrencesOfString:@"_" withString:@""];        if ([keyName isEqualToString:name]) {            return YES;        }    }    return NO;}

高级iOS开发技术交流群:415239068,欢迎大家加入



0 0
原创粉丝点击