美文网首页
Category添加属性

Category添加属性

作者: 码省理工0 | 来源:发表于2016-12-19 23:38 被阅读19次

    通过runtime的两种方法就可以为类别添加一个实例变量了。

    #import <Foundation/Foundation.h>
     @interface NSObject (IndieBandName)
     @property (nonatomic, copy) NSString *indieBandName;
     @end
    
    #import "NSObject+IndieBandName.h"
    #import <objc/runtime.h>
    //设置关联的key
    static const void *IndieBandNameKey = &IndieBandNameKey;
    
    @implementation NSObject (IndieBandName)
     - (NSString *)indieBandName {
        return objc_getAssociatedObject(self, IndieBandNameKey);
    }
    
      - (void)setIndieBandName:(NSString *)indieBandName{
    //Associated关联
        objc_setAssociatedObject(self, IndieBandNameKey, indieBandName, OBJC_ASSOCIATION_COPY_NONATOMIC);
    }
    @end

    相关文章

      网友评论

          本文标题:Category添加属性

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