Method Swizzling 方法混合

Method Swizzling 方法混合,第1张

概述    在前文深入浅出Cocoa之消息中,我简要介绍了ObjC 中消息的基本情况,包括SEL查找,缓存以及消息转发等。在本文中,我要介绍一个很有趣的技术,Methodswizzling,通过这个手法,我们可以动态修改方法的实现,从而达到修改类行为的目的。当然,还有其他办法(如ClassPosing,Category)也可以达到这个目的。ClassPosing是针对类级别的,是重量级的手法,Cate

 

 

在前文深入浅出Cocoa之消息中,我简要介绍了ObjC 中消息的基本情况,包括SEL查找,缓存以及消息转发等。在本文中,我要介绍一个很有趣的技术,Methodswizzling,通过这个手法,我们可以动态修改方法的实现,从而达到修改类行为的目的。当然,还有其他办法(如ClassPosingcategory)也可以达到这个目的。Classposing是针对类级别的,是重量级的手法,category 也差不多,比较重量级,此外 category 还无法避免下面的递归死循环(如果你的代码出现了如下形式的递归调用,应该考虑一下你的设计,而不是使用在这里介绍的 MethodSwizzling 手法,:))。

// bar
//
@implementation bar

- (
voID) testMethod
{
   
NSLog(@" >> bar testMethod");
}

@end

// bar(barcategory)
//
@implementation bar(barcategory)

- (
voID) altRecursionMethod
{
   
NSLog(@" >> bar(barcategory) recursionMethod");
   
[self altRecursionMethod];
}

@end

在前文深入浅出Cocoa之消息中提到,ObjC 中的类(class)和实例(instance)都是对象,类对象有自己的类方法列表,实例对象有自己的实例方法列表,这些方法列表(structobjc_method_List)是存储在 structobjc_class 中的。每个方法列表存储近似SEL:Method 的对,Method 是一个对象,包含方法的具体实现 impl。由此可知,我们只需要修改 SEL 对应的 Method impl 既可以达到修改消息行为的目的。下面来看代码:

voID PerformSwizzle(Class aClass,SEL orig_sel,SEL alt_sel,BOolforInstance)
{
   
// First,make sure the class isn't nil
   if (aClass != nil) {
       
Method orig_method = nil,alt_method = nil;

        // Next,look for the methods
        if (forInstance) {
           
orig_method =class_getInstanceMethod(aClass,orig_sel);
            alt_method =class_getInstanceMethod(aClass,alt_sel);
        } else {
           
orig_method =class_getClassMethod(aClass,orig_sel);
            alt_method = class_getClassMethod(aClass,alt_sel);
        }

        // If both are found,swizzle them
        if ((orig_method != nil) &&(alt_method != nil)) {
           
IMP temp;

            temp =orig_method->method_imp;
            orig_method->method_imp =alt_method->method_imp;
            alt_method->method_imp =temp;
        } else {
#if DEBUG
           
NSLog(@"PerformSwizzle Error: Original %@,Alternate %@",(orig_method == nil)?@" not found":@" found",(alt_method== nil)?@" not found":@" found");
#endif
     
  }
    } else {
#if DEBUG
       
NSLog(@"PerformSwizzle Error: Class not found");
#endif
   
}
}

voID MethodSwizzle(Class aClass,SEL alt_sel)
{
   
PerformSwizzle(aClass,orig_sel,alt_sel,YES);
}

voID ClassMethodSwizzle(Class aClass,NO);
}


让我们来分析上面代码:
1
,首先,区分类方法和实例方法;
2
,取得 SEL 对应的 Method
3
,修改 Method impl,在这里是通过交换实现的。

上面的代码是可以工作的,但还不够完善。Apple 10.5提供了交换 Method 实现的 API: method_exchangeImplementations。下面我们使用这个新 API,并以 NSObject category的形式给出新的实现方式:

#if TARGET_OS_IPHONE
#import <objc/runtime.h>
#import <objc/message.h>
#else
#import <objc/objc-
class.h>
#endif

// NSObject (MethodSwizzlingcategory)
//
@interface NSObject(MethodSwizzlingcategory)

+ (BOol)swizzleMethod:(SEL)origSel withMethod:(SEL)altSel;
+ (BOol)swizzleClassMethod:(SEL)origSel withClassMethod:(SEL)altSel;

@end

@implementation NSObject (MethodSwizzlingcategory)

+ (BOol)swizzleMethod:(SEL)origSel withMethod:(SEL)altSel
{
   
Method origMethod =class_getInstanceMethod(self,origSel);
    if (!origSel) {
       
NSLog(@"original method %@ not found for class %@",NsstringFromSelector(origSel),[self class]);
       
return NO;
   
}
   
    Method altMethod =class_getInstanceMethod(self,altSel);
    if (!altMethod) {
       
NSLog(@"original method %@ not found for class %@",NsstringFromSelector(altSel),[self class]);
       
return NO;
   
}
   
    class_addMethod(self,
                    origSel,
                   class_getmethodImplementation(self,origSel),
                   method_getTypeEnCoding(origMethod));
    class_addMethod(self,
                    altSel,altSel),
                   method_getTypeEnCoding(altMethod));
   
   method_exchangeImplementations(class_getInstanceMethod(self,class_getInstanceMethod(self,altSel));

    return YES;
}

+ (BOol)swizzleClassMethod:(SEL)origSel withClassMethod:(SEL)altSel
{
   
Class c = object_getClass((ID)self);
    return [cswizzleMethod:origSel withMethod:altSel];
}

@end

代码就不用多解释了,下面我们来看如何使用。先看辅助类Foo
Foo.h

//
// 
Foo.h
//  MethodSwizzling
//
//  Created by LuoZhaohui on 1/5/12.
//  copyright (c) 2012 http://www.cnblogs.com/kesalin/. All rightsreserved.
//

#import <Foundation/Foundation.h>

// Foo
//
@interface Foo : NSObject

- (
voID) testMethod;
- (
voID) baseMethod;
- (
voID) recursionMethod;

@end

// bar
//
@interface bar : Foo

- (
voID) testMethod;

@end

// bar(barcategory)
//
@interface bar(barcategory)

- (
voID) altTestMethod;
- (
voID) altBaseMethod;
- (
voID) altRecursionMethod;

@end

Foo.m

//
// 
Foo.m
//  MethodSwizzling
//
//  Created by LuoZhaohui on 1/5/12.
//  copyright (c) 2012 http://www.cnblogs.com/kesalin/. All rights reserved.
//

#import
"Foo.h"

// Foo
//
@implementation Foo

- (
voID) testMethod
{
   
NSLog(@" >> Foo testMethod");
}

- (
voID) baseMethod
{
   
NSLog(@" >> Foo baseMethod");
}

- (
voID) recursionMethod
{
   
NSLog(@" >> Foo recursionMethod");
}

@end

// bar
//
@implementation bar

- (
voID) testMethod
{
   
NSLog(@" >> bar testMethod");
}

@end

// bar(barcategory)
//
@implementation bar(barcategory)

- (
voID) altTestMethod
{
   
NSLog(@" >> bar(barcategory) altTestMethod");
}

- (
voID) altBaseMethod
{
   
NSLog(@" >> bar(barcategory) altBaseMethod");
}

- (
voID) altRecursionMethod
{
   
NSLog(@" >> bar(barcategory) recursionMethod");
   
[self altRecursionMethod];
}

@end

下面是具体的使用示例:

int main (int argc,constchar * argv[])
{
   
@autoreleasepool
    {
        Foo * foo = [[[Foo alloc] init]autorelease];
        bar * bar = [[[bar alloc] init]autorelease];
       
        NSLog(@"========= Method Swizzling test 1 =========");
       

        NSLog(@" Step 1");
       
[foo testMethod];
        [bar testMethod];
        [bar altTestMethod];
       
        NSLog(@" Step 2");
       
[barswizzleMethod:@selector(testMethod) withMethod:@selector(altTestMethod)];
        [foo testMethod];
        [bar testMethod];
        [bar altTestMethod];
       
        NSLog(@"========= Method Swizzling test 2 =========");
       
NSLog(@" Step 1");
       
[foo baseMethod];
        [bar baseMethod];
        [bar altBaseMethod];
       
        NSLog(@" Step 2");
       
[barswizzleMethod:@selector(baseMethod) withMethod:@selector(altBaseMethod)];
        [foo baseMethod];
        [bar baseMethod];
        [bar altBaseMethod];
       
        NSLog(@"========= Method Swizzling test 3 =========");
       
[barswizzleMethod:@selector(recursionMethod) withMethod:@selector(altRecursionMethod)];
        [bar recursionMethod];
    }

    return0;
}


输出结果为:注意,test 3 中调用了递归调用自己的方法,你能理解为什么没有出现死循环么?

========= Method Swizzling test 1=========
Step 1
>> Foo testMethod
>> bar testMethod
>> bar(barcategory) altTestMethod
Step 2
>> Foo testMethod
>> bar(barcategory) altTestMethod
>> bar testMethod
========= Method Swizzling test 2 =========
Step 1
>> Foo baseMethod
>> Foo baseMethod
>> bar(barcategory) altBaseMethod
Step 2
>> Foo baseMethod
>> bar(barcategory) altBaseMethod
>> Foo baseMethod
========= Method Swizzling test 3 =========
>> bar(barcategory) recursionMethod
>> Foo recursionMethod

rentzsch 写了一个完善的开源类jrswizzle来处理 Method Swizzling,如果你在工程中使用到MethodSwizzling 手法,应该优先使用这个类库,:)。

Refference

MethodSwizzlinghttp://www.cocoadev.com/index.pl?ExtendingClasses

jrswizzlehttps://github.com/rentzsch/jrswizzle

总结

以上是内存溢出为你收集整理的Method Swizzling 方法混合全部内容,希望文章能够帮你解决Method Swizzling 方法混合所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1055100.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存