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

ios中给分类添加属性

作者: NJKNJK | 来源:发表于2019-09-27 14:20 被阅读0次

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

    1.先创建一个分类,以下以UIImage为例子。

    2.增加需要的属性。

    3.导入runtime框架,重写set方法和get方法。

    
    @interface UIImage (NJKUIImage)
    
    @property(nonatomic, assign)NSInteger       tag;
    @property(nonatomic, copy)NSString          *name;
    @property(nonatomic, strong)NSDate          *data;
    
    @end
    
    
    
    #import "UIImage+NJKUIImage.h"
    #import <objc/runtime.h>
    
    @implementation UIImage (NJKUIImage)
    
    static const void *njk_view_tag = @"njk_image_tag";
    static const void *njk_view_name = @"njk_view_name";
    static const void *njk_view_data = @"njk_view_data";
    
    - (void)setTag:(NSInteger)tag{
    //常量属性只需要转换一下
        NSString *string = [NSString stringWithFormat:@"%ld",(long)tag];
        objc_setAssociatedObject(self, &njk_view_tag, string, OBJC_ASSOCIATION_COPY_NONATOMIC);
    }
    - (NSInteger)tag{
    //常量属性读取时也需要添加转换
        return [objc_getAssociatedObject(self, &njk_view_tag)integerValue];
    }
    
    - (void)setName:(NSString *)name{
        objc_setAssociatedObject(self, njk_view_name, name, OBJC_ASSOCIATION_COPY_NONATOMIC);
    }
    - (NSString *)name{
        return objc_getAssociatedObject(self, njk_view_name);
    }
    
    - (void)setData:(NSDate *)data{
        objc_setAssociatedObject(self, &njk_view_data, data, OBJC_ASSOCIATION_COPY_NONATOMIC);
    }
    - (NSDate *)data{
        return objc_getAssociatedObject(self, &njk_view_data);
    }
    
    @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/vgxauctx.html