iOS 运行时runtime应用之二--在category中使用运行时API给类添加属性

例证:

#import <UIKit/UIKit.h>
#interface UIImage (Extension)
#property(nonatomic,assign)CGFloat borderWidth; // 边框宽度
@property(nonatomic,strong)UIColor *borderColor;   //边框颜色
- (UIImage*)circle;
@end

@import "UIImage+Extension.h"
@import <objc/runtime.h>
/** 每个属性关联的关键字是唯一的 所以使用常量定义 */
static const char *lyy_image_borderWidthKey = "lyy_image_borderWidthKey";
static const char *lyy_image_borderColorKey =  "lyy_image_borderColorKey";

@implementation UIImage (Extension)
- (UIImage*)circle{
    return nil;
}

- (void)setBorderWidth:(CGFloat )borderWidth{
    objc_setAssociatedObject(self, lyy_image_borderWidthKey, @(borderWidth), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (CGFloat)borderWidth{
    id width = objc_getAssociatedObject(self, lyy_image_borderWidthKey);
    if ([width respondsToSelector:@selector(doubleValue)]) {
        return  [width doubleValue];
    }
    return 0; //默认为0
}

- (void)setBorderColor:(UIColor*)borderColor{
    objc_setAssociatedObject(self, lyy_image_borderColorKey, borderColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIColor*)borderColor{
    UIColor *color = objc_getAssociatedObject(self, lyy_image_borderColorKey);
    if(color){  // 判断 让你的思维变得更加缜密
        return color;  
    }
    return [UIColor whiteColor]; //默认为白色
}
@end

通过运行时的API,实现了给UIImage类添加了两个属性 borderWidth(边框宽度);borderColor(边框颜色)

你可能感兴趣的:(iOS 运行时runtime应用之二--在category中使用运行时API给类添加属性)