本文將介紹如何利用運行時機制動態(tài)給現(xiàn)有的類添加屬性,分OC和Swift兩個版本
一 OC版:OC給現(xiàn)有類添加屬性只需要利用OC的分類機制就行,給現(xiàn)有類添加一個categery,然后利用runtime的兩個api即可做到?,F(xiàn)在我們給UIButton 添加一個image屬性。
第一步給UIButton提供一個分類在分類的UIButton+Extension.h文件中代碼如下:
#import <UIKit/UIKit.h>
@interface UIButton (Extension)
@property (nonatomic,strong)UIImage *image;
@end
第二步,在分類的UIButton+Extension.m文件中利用runtime的api給出image的get和set方法:
#import "UIButton+Extension.h"
#import <objc/runtime.h>
@implementation UIButton (Extension)
static const voidvoid *zc_image_key = @"zc_image_key";
- (void)setImage:(UIImage *)image {
if (image != self.image) {
//添加新的
objc_setAssociatedObject(self, zc_image_key, image, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
}
- (UIImage *)image {
return objc_getAssociatedObject(self, zc_image_key);
}
@end
第三步,使用:
UIButton *button = [[UIButton alloc] init];
UIImage *image = [[UIImage alloc] init];
button.image = image;
二:swift版本可以利用extension,UIButton+Extension.swift具體代碼如下:
import UIKit
extension UIButton {
static let zc_image_key = UnsafeRawPointer.init(bitPattern: "zc_image_key".hashValue)
var image: UIImage? {
set {
objc_setAssociatedObject(self, UIButton.zc_image_key, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, UIButton.zc_image_key) as? UIImage
}
}
}