Aspects 来进行方法的拦截
利用 runtime,方法交换
拦截器的应用-通知 kvo
iOS runtime实战应用:Method Swizzling
AOP~
AOP轮子
Method Swizzling固定格式如下
替换 uilabel的setText 为 typeset_setText
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSelector = @selector(setText:);
SEL swizzledSelector = @selector(typeset_setText:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL didAddMethod =
class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
- (void)typeset_setText:(NSString *)text {
if (self.typesetBlock && text) {
self.attributedText = self.typesetBlock(text);
} else {
[self typeset_setText:text];
}
}
eg: 拦截text改变完整代码如下
.h
#import <UIKit/UIKit.h>
@interface UILabel (Typeset)
@property (nonatomic, copy) NSAttributedString *(^typesetBlock)(NSString *string);
@end
.m
#import "UILabel+Typeset.h"
#import <objc/runtime.h>
@implementation UILabel (Typeset)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSelector = @selector(setText:);
SEL swizzledSelector = @selector(typeset_setText:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL didAddMethod =
class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
- (void)typeset_setText:(NSString *)text {
if (self.typesetBlock && text) {
self.attributedText = self.typesetBlock(text);
} else {
[self typeset_setText:text];
}
}
- (NSAttributedString *(^)(NSString *))typesetBlock {
return objc_getAssociatedObject(self, @selector(typesetBlock));
}
- (void)setTypesetBlock:(NSAttributedString *(^)(NSString *))typesetBlock {
if (self.text && typesetBlock) self.attributedText = typesetBlock(self.text);
objc_setAssociatedObject(self, @selector(typesetBlock), [typesetBlock copy], OBJC_ASSOCIATION_COPY_NONATOMIC);
}
@end