#import <objc/runtime.h>
#ifndef DYNAMIC_PROPERTY_OBJECT
#define DYNAMIC_PROPERTY_OBJECT(_getter_, _setter_, _association_, _type_) \
- (void)_setter_ : (_type_)object { \
[self willChangeValueForKey:@#_getter_]; \
objc_setAssociatedObject(self, _cmd, object, OBJC_ASSOCIATION_ ## _association_); \
[self didChangeValueForKey:@#_getter_]; \
} \
- (_type_)_getter_ { \
return objc_getAssociatedObject(self, @selector(_setter_:)); \
}
#endif
void swizzlingMethod(Class c, SEL origSEL, SEL newSEL);
void swizzlingMethod(Class class, SEL originSEL, SEL swizzledSEL)
{
Method originMethod = class_getInstanceMethod(class, originSEL);
Method swizzledMethod = nil;
if (!originMethod) {// 处理为类方法
originMethod = class_getClassMethod(class, originSEL);
if (!originMethod) {
return;
}
swizzledMethod = class_getClassMethod(class, swizzledSEL);
if (!swizzledMethod) {
return;
}
}else {// 处理实例方法
swizzledMethod = class_getInstanceMethod(class, swizzledSEL);
if (!swizzledMethod){
return;
}
}
if(class_addMethod(class, originSEL, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))){
class_replaceMethod(class, swizzledSEL, method_getImplementation(originMethod), method_getTypeEncoding(originMethod));
}else {
//自身已经有了就添加不成功,直接交换即可
method_exchangeImplementations(originMethod, swizzledMethod);
}
}
网友评论