iOS runtime之关联对象AssociatedObject的使用

在分类中添加属性,使用对象关联来实现:

例子:创建一个label的分类

#import

@interfaceUILabel (FontAndColor)

@property (nonatomic, copy) NSString *name;//分类中创建了一个name属性

-(void)WithFont:(int)font withColor:(UIColor*)color withTextAlig:(NSTextAlignment)texAli;

@end


#import "UILabel+FontAndColor.h"

#import

@implementationUILabel (FontAndColor)

static NSString *key = @"associatedObject";

-(void)WithFont:(int)font withColor:(UIColor*)color withTextAlig:(NSTextAlignment)texAli{

    self.font = [UIFont systemFontOfSize:font];

    self.textColor= color;

    self.textAlignment= texAli;

}

-(void)setName:(NSString*)name{//关联实现

    objc_setAssociatedObject(self, @selector(name), name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}

-(NSString*)name{//获取值

    return objc_getAssociatedObject(self, _cmd);

}

@end

你可能感兴趣的:(iOS runtime之关联对象AssociatedObject的使用)