本文将介绍如何利用运行时机制动态给现有的类添加属性,分OC和Swift两个版本
一 OC版:OC给现有类添加属性只需要利用OC的分类机制就行,给现有类添加一个categery,然后利用runtime的两个api即可做到。现在我们给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
}
}
}