Category关联属性
为一个对象设置关联对象,实现为其添加属性的效果,使用方法
objc_setAssociatedObject
objc_getAssociatedObject
UIView+LeoExtension.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface UIView (LeoExtension)
@property (copy,nonatomic)NSString * leo_anaylizeTitle;
@end
UIView+LeoExtension.m
#import "UIView+LeoExtension.h"
#import <objc/runtime.h>
static const char kAnaylizeTitle;
@implementation UIView (LeoExtension)
-(NSString *)leo_anaylizeTitle{
return objc_getAssociatedObject(self, &kAnaylizeTitle);
}
-(void)setLeo_anaylizeTitle:(NSString *)leo_anaylizeTitle{
objc_setAssociatedObject(self, &kAnaylizeTitle,leo_anaylizeTitle, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
@end
Method Swizzling
#import <objc/runtime.h>
@implementation UIViewController (Tracking)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSelector = @selector(viewWillAppear:);
SEL swizzledSelector = @selector(xxx_viewWillAppear:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
// When swizzling a class method, use the following:
// Class class = object_getClass((id)self);
// ...
// Method originalMethod = class_getClassMethod(class, originalSelector);
// Method swizzledMethod = class_getClassMethod(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);
}
});
}
#pragma mark - Method Swizzling
- (void)xxx_viewWillAppear:(BOOL)animated {
[self xxx_viewWillAppear:animated];
NSLog(@"viewWillAppear: %@", self);
}
@end
交叉后的Runtime顺序:
- 根据@selector(viewWillAppear:)找到自定义的xxx_viewWillAppear实现
- 自定义的xxx_viewWillAppear实现,向Self发送@selector(xxx_viewWillAppear)
- 根据@selector(xxx_viewWillAppear),找到默认的SDK中viewWillAppear的实现
- 执行默认SDK中viewWillAppear代码
- 执行NSLog(@"viewWillAppear: %@", self);
- 结束