iOS runtime消息转发机制等

消息转发机制分可以为三步,第一步:动态方法解析,询问该类是否能动态添加该方法,执行方法为resolveInstanceMethod; 第二步:询问是否有其他对象处理该消息,执行方法为forwardingTargetForSelector; 第三步:把该消息封装到NSInvocation对象中处理,执行方法为forwardInvocation.

消息转发基本流程如下图:


iOS runtime消息转发机制等_第1张图片
消息转发.png

1. 动态方法解析

对象在收到无法解读的消息时,会调用所属类的下列方法:

+ (BOOL)resolveClassMethod:(SEL)sel OBJC_AVAILABLE;
+ (BOOL)resolveInstanceMethod:(SEL)sel OBJC_AVAILABLE;

分别为类方法和实例方法,参数sel就是未能处理的选择器,返回值为BOOL类型,表示这个类是否新增一个方法来处理该 sel,下面只讨论实例方法演示代码如下:

  NSString *obj = [YTestObject new];
  [obj uppercaseString];

//YTestObject.m
+ (BOOL)resolveInstanceMethod:(SEL)sel {
    NSLog(@"%s",__func__);
    if (sel == @selector(uppercaseString)) {
        return class_addMethod([self class], sel, (IMP)uppercaseString, "v@:");
    } 
    return [super resolveInstanceMethod:sel];
}

void uppercaseString(id self,SEL _cmd) {
    NSLog(@"%s",__func__);
}

class_addMethod的定义为BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types),参数说明:

  • cls:要添加方法的类
  • name:选择器
  • imp:方法实现,IMP在objc.h中的定义是:typedef id (*IMP)(id, SEL, ...);该方法至少有两个参数,self(id)和_cmd(SEL)
  • types:方法,参数和返回值的描述,"v@:"表示返回值为void,没有参数,这些编码参考Type Encoding

如果你想让该方法选择器被传送到转发机制,那么就让resolveInstanceMethod:返回NO

2. 消息重定向

在这一步中,可以把消息转给其他对象replacement receiver;改变该 Selector的调用对象,对应方法:
- (id)forwardingTargetForSelector:(SEL)aSelector
参数aSelector为未能处理的选择器,返回其他处理该消息的对象或者nil,演示代码如下:

- (id)forwardingTargetForSelector:(SEL)aSelector {
    NSLog(@"%s",__func__);
    if (aSelector == @selector(lowercaseString)) {
        return [YTestObjectB new];
    }
    return [super forwardingTargetForSelector:aSelector];
}

这样lowercaseString选择器就已经重新定向给YTestObjectB;具体运行可以看最后给出的demo.

3. 消息转发

消息转发也是改变调用对象,使该消息在新对象上调用;不同是forwardInvocation方法带有一个NSInvocation对象,这个对象保存了这个方法调用的所有信息,包括SEL,参数和返回值描述等,JSPatch就是基于消息转发实现的,这一步需要实现以下两个方法:

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector ;
- (void)forwardInvocation:(NSInvocation *)anInvocation ;

因为消息转发也是改变调用对象,第二步就能实现,所以不深究,演示代码给出最基本的无返回值,无参数示例:

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    NSLog(@"%s",__func__);
    return [NSMethodSignature signatureWithObjCTypes:"v@:"];
}

- (void)forwardInvocation:(NSInvocation *)anInvocation {
    NSLog(@"%s",__func__);
    if (anInvocation.selector == @selector(capitalizedString)) {
        [anInvocation invokeWithTarget:[YTestObjectB new]];
        return;
    }
    [super forwardInvocation:anInvocation];
}

4. Associated Objects

在 OS X 10.6 之后,Runtime支持OC给对象动态添加变量,涉及到的函数有以下三个:

void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy);
id objc_getAssociatedObject(id object, const void *key);
void objc_removeAssociatedObjects(id object);

其中key为关联键值, policy为关联策略,定义如下:

typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {
    OBJC_ASSOCIATION_ASSIGN = 0,           /**< Specifies a weak reference to the associated object. */
    OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object. 
                                            *   The association is not made atomically. */
    OBJC_ASSOCIATION_COPY_NONATOMIC = 3,   /**< Specifies that the associated object is copied. 
                                            *   The association is not made atomically. */
    OBJC_ASSOCIATION_RETAIN = 01401,       /**< Specifies a strong reference to the associated object.
                                            *   The association is made atomically. */
    OBJC_ASSOCIATION_COPY = 01403          /**< Specifies that the associated object is copied.
                                            *   The association is made atomically. */
};

演示代码,用CategoryNSString增加一个属性:

//NSString+YCategory.h
@property (assign, nonatomic) NSUInteger stringLength;

//NSString+YCategory.m
static const void *kStringLength = "kStringLength";
@dynamic stringLength;
- (void)setStringLength:(NSUInteger)stringLength {
    objc_setAssociatedObject(self, kStringLength, @(stringLength), OBJC_ASSOCIATION_ASSIGN);
}

- (NSUInteger)stringLength {
    id len = objc_getAssociatedObject(self, kStringLength);
    return [len unsignedIntegerValue];
}

5. Method Swizzling

当我们无法查看到某个类的源代码,但却想更改这个类某个方法的实现时,或者项目中为了方便添加一些埋点等,可以使用Method Swizzling,演示代码:

+ (void)swizzleSelector:(SEL)originSel replaceSel:(SEL)replaceSel {
    Method originalMethod = class_getInstanceMethod(self, originSel);
    Method overrideMethod = class_getInstanceMethod(self, replaceSel);
    if (class_addMethod(self, originSel, method_getImplementation(overrideMethod), method_getTypeEncoding(overrideMethod))) {
        class_replaceMethod(self, replaceSel, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, overrideMethod);
    }
}

//ViewController.m
+ (void)load {
    NSLog(@"%s",__func__);
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [ViewController swizzleSelector:@selector(viewWillAppear:) replaceSel:@selector(my_viewWillAppear:)];
    });
}

Swizzling 放在一个类的load方法中,因为load是在一个类最开始加载时调用的,再用dispatch_once保证代码块只执行一次,且线程安全.上面的方法实际交换了viewWillAppearmy_viewWillAppearIMP,系统调用viewWillAppear方法时,实际运行到my_viewWillAppear的实现里,然后在my_viewWillAppear的实现里调用[self my_viewWillAppear:animated];执行原本viewWillAppear的代码.

6. 介绍一个类NSObject+DLIntrospection

DLIntrospection利用runtime输出类的属性,实例方法,类方法等.具体功能如下:

+ (NSArray *)classes;
+ (NSArray *)properties;
+ (NSArray *)instanceVariables;
+ (NSArray *)classMethods;
+ (NSArray *)instanceMethods;

+ (NSArray *)protocols;
+ (NSDictionary *)descriptionForProtocol:(Protocol *)proto;

+ (NSString *)parentClassHierarchy;

此类和lldb一起使用非常方便,DLIntrospection下载地址

此外,runtime详细介绍,可以看这个,还可以下载runtime源码,最后,demo地址

你可能感兴趣的:(iOS runtime消息转发机制等)