iOS分类添加属性

我们可以通过runtime来给iOS的分类添加属性.

想添加属性,记住几个关键词,1.@dynamic 2.Associated

1. 首先我们像普通的类一样在.h里头使用@property声明一个属性
    ///xxx+CH.h.这里是xxx类的CH分类的.h文件
    @interface xxx (CH)

    @property (nonatomic ,strong) NSString *name;

    @end

这时,.m中就会出现两个警告

    Property 'name' requires method 'name' to be defined - use @dynamic or provide a method implementation in this category
    Property 'name' requires method 'setName:' to be defined - use @dynamic or provide a method implementation in this category

这时.我们在.m中使用@dynamic修饰一下这个属性名字就没有警告了.

    //xxx+CH.m
    @implementation xxx (CH)

    @dynamic name;

    @end
2.使用runtime的方法动态绑定属性.(“重写”get-set方法)
    ///1.
    //xxx+CH.m
    #import <objc/runtime.h>///记得别忘记导入objc/runtime.h

    @implementation xxx (CH)

    @dynamic name;

    /// name的key
    static char *nameKey = "nameKey";

    - (void)setName:(NSString *)name {
        objc_setAssociatedObject(self, nameKey, name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }

    - (NSString *)name {
        id name = objc_getAssociatedObject(self, nameKey);
        if (name) {
            return name;
        } else {
            return @"";
        }
    }

    @end

到此为止,我们就给分类添加好属性了.

注意点:
1.对象有哪些类型

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

2.非对象类型的取值.我们可以使用id的getValue来去取值去返回.

    例: 这里我们取一个CGRect值
    - (CGRect)rect {
        id rectResult = objc_getAssociatedObject(self, rectKey);
        if (rect) {
            CGRect rect;
            [rectResult getValue:&rect];
            return rect;
        } else {
            return CGRectZero;
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值