美文网首页
iOS runtime之关联对象AssociatedObject

iOS runtime之关联对象AssociatedObject

作者: 逆世界开发者 | 来源:发表于2018-08-28 20:32 被阅读0次

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

    例子:创建一个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

          本文链接:https://www.haomeiwen.com/subject/mxtcwftx.html