ios中给分类添加属性

2018-04-23  本文已影响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. */
};
上一篇 下一篇

猜你喜欢

热点阅读