关联:objc_getAssociatedObject和objc_setAssociatedObject使用

为UIButton的category添加属性

UIButton+subTitle.h

#import <UIKit/UIKit.h>

#import <objc/runtime.h>

 

@interface UIButton (subTitle)

@property (nonatomic, copy) NSString *subTitle;

@property (nonatomic, strong) UIColor *foreColor;

//此处添加int类型属性不能使用,因为objc需要用id类型,此处留着以后修改

@property (nonatomic) int tagAdd;

@end

 

UIButton+subTitle.m

#import "UIButton+subTitle.h"

 

@implementation UIButton (subTitle)

 

static char oooo;

 

- (NSString *)subTitle{

 

    return objc_getAssociatedObject(self, @selector(subTitle));

}

- (void)setSubTitle:(NSString *)subTitle{

    [self setTitle:subTitle forState:UIControlStateNormal];

    objc_setAssociatedObject(self, @selector(subTitle), subTitle, OBJC_ASSOCIATION_COPY_NONATOMIC);

}

- (UIColor *)foreColor{

    return objc_getAssociatedObject(self, @selector(foreColor));

}

- (void)setForeColor:(UIColor *)foreColor{

    self.backgroundColor = foreColor;

    objc_setAssociatedObject(self, @selector(foreColor), foreColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}

 

- (void)setTagAdd:(int)tagAdd{

    objc_setAssociatedObject(self, &oooo, @(tagAdd), OBJC_ASSOCIATION_ASSIGN);

}

- (int)tagAdd{

    return (int)objc_getAssociatedObject(self, &oooo);

}

 

posted on 2016-01-20 13:40  On1Key  阅读(244)  评论(0编辑  收藏  举报

导航