iOS 给已有的类添加属性.

比如说给UIView 添加一个name 的属性,

步骤:

1. 创建 UIView + addProperty.h / UIView + addProperty.m 的类目,

然后在UIView + addProperty.h 中添加一个属性,

 

@property(nonatomic,strong)NSString *name;

 2. 在.m  中重写get /set 方法.

@dynamic name;

 

static char charKey;

- (void)setName:(NSString *)name

{

    objc_setAssociatedObject(self, &charKey, name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}

 

- (NSString *)name

{

    return objc_getAssociatedObject(self, &charKey);

}

 

3. 解释一下 objc_setAssociatedObject 方法

 //1 源对象(在这里 是给view 添加的属性,所以 就是 view 自己)

    //2 关键字 唯一静态变量key associatedkey

    //3 关联的对象 ,这个地方是name值,sender

    //4 关键策略  OBJC_ASSOCIATION_ASSIGN

    //    enum {

    //        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. */

    //    };

 

posted @ 2016-09-18 16:43  lanacon  Views(1580)  Comments(0Edit  收藏  举报