category

category使用 objc_setAssociatedObject/objc_getAssociatedObject 实现添加属性

属性 其实就是get/set 方法。我们可以使用  objc_setAssociatedObject/objc_getAssociatedObject  实现 动态向类中添加 方法


@interface NSObject (CategoryWithProperty)

@property (nonatomic, strong) NSObject *property;

@end

@implementation NSObject (CategoryWithProperty)

- (NSObject *)property {
    return objc_getAssociatedObject(self, @selector(property));
}

- (void)setProperty:(NSObject *)value {
    objc_setAssociatedObject(self, @selector(property), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

objective-c中,有类别可以在不修改源码的基础上增加方法;近排在看别人的开源代码时,发现还可以动态增加属性。而且是在运行时,太牛B了。

使用运行时库,必须要先引入 objc/runtime.h

可以使用的函数如下:

OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)

这个函数


OBJC_EXPORT id objc_getAssociatedObject(id object, const void *key)
__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1);

 

兄弟们,看一个类别和动态添加属性的例子:

UILabel+Associate.h

复制代码
#import <UIKit/UIKit.h>

@interface UILabel (Associate)

- (void) setFlashColor:(UIColor *) flashColor;

- (UIColor *) getFlashColor;

@end
复制代码

UILabel+Associate.m

复制代码
#import "UILabel+Associate.h"
#import <objc/runtime.h>

@implementation UILabel (Associate)

static char flashColorKey;

- (void) setFlashColor:(UIColor *) flashColor{
    objc_setAssociatedObject(self, &flashColorKey, flashColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIColor *) getFlashColor{
   return objc_getAssociatedObject(self, &flashColorKey);
}

@end
复制代码

调用代码:

UILabel *lab = [[UILabel alloc] init];
    [lab setFlashColor:[UIColor redColor]];
    NSLog(@"%@", [lab getFlashColor]);


//

//  UIAlertView+ShowWithBlock.h



#import <UIKit/UIKit.h>

typedef void (^alertBlock)(UIAlertView *alertView, NSInteger buttonIndex);


@interface UIAlertView (UIAlertView_Category)<UIAlertViewDelegate>


-(void)showWithBlock:(alertBlock)block;


@end


//  UIAlertView+ShowWithBlock.m


#import "UIAlertView+Category.h"

#import <objc/runtime.h>


static NSString *MyAlertAction = @"MyAlertAction";


@implementation UIAlertView (UIAlertView_Category)



- (void)showWithBlock:(alertBlock)block

{

    if (block){

        objc_removeAssociatedObjects(self);

        objc_setAssociatedObject(self, (__bridge const void *)(MyAlertAction), block, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

        self.delegate = self;

    }

    [self show];

}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{

    alertBlock block = objc_getAssociatedObject(self, (__bridge const void *)(MyAlertAction));

    block(alertView, buttonIndex);

}


@end



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值