美文网首页
ios中给分类添加属性

ios中给分类添加属性

作者: 陈藩 | 来源:发表于2018-04-23 10:51 被阅读0次

    ios中利用类别给已有的类扩展方法是可以的,但是如果直接的添加属性是会报错的。利用runtime可以达到添加属性的目的。

    1.先创建一个分类,以下以UIImage为例子。
    2.增加一个属性。
    3.导入runtime框架,重写set方法和get方法

    
    @interface UIImage (Name)
    
    @property (nonatomic,copy) NSString * name;
    
    @end
    
    #import <objc/runtime.h>
    
    @implementation UIImage (Name)
    
    static const void *classNameKey = &classNameKey;
    
    -(void)setName:(NSString *)name{
        objc_setAssociatedObject(self, classNameKey, name,  OBJC_ASSOCIATION_COPY_NONATOMIC);
    }
    
    -(NSString *)name{
       return  objc_getAssociatedObject(self, classNameKey);
    }
    
    @end
    
    

    //其中注意以下的参数是用来表示创建的属性的类型的

    
    typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {
        OBJC_ASSOCIATION_ASSIGN = 0,           /**< Specifies a weak reference to the associated object. */
        OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object. 
                                                *   The association is not made atomically. */
        OBJC_ASSOCIATION_COPY_NONATOMIC = 3,   /**< Specifies that the associated object is copied. 
                                                *   The association is not made atomically. */
        OBJC_ASSOCIATION_RETAIN = 01401,       /**< Specifies a strong reference to the associated object.
                                                *   The association is made atomically. */
        OBJC_ASSOCIATION_COPY = 01403          /**< Specifies that the associated object is copied.
                                                *   The association is made atomically. */
    };
    

    相关文章

      网友评论

          本文标题:ios中给分类添加属性

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