qinguo2000的专栏

使用运行时库,必须要先引入 objc/runtime.h

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

UILabel+Associate.h#import <UIKit/UIKit.h>@interface UILabel (Associate)- (void) setFlashColor:(UIColor *) flashColor;- (UIColor *) getFlashColor;@endUILabel+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,,欢迎大家加入

旅游时最好的习惯:找个舒适的小店,挑张雅致的明信片,

qinguo2000的专栏

相关文章:

你感兴趣的文章:

标签云: