0
点赞
收藏
分享

微信扫一扫

ios runtime之方法交换

颜路在路上 2021-09-29 阅读 77
iOS OC开发
/**
 * Exchanges the implementations of two methods.(交换两个方法的实现。)
 *
 * @param m1 Method to exchange with second method.
 * @param m2 Method to exchange with first method.
 *
 * @note This is an atomic version of the following:
 *  \code
 *  IMP imp1 = method_getImplementation(m1);
 *  IMP imp2 = method_getImplementation(m2);
 *  method_setImplementation(m1, imp2);
 *  method_setImplementation(m2, imp1);
 *  \endcode
 */
OBJC_EXPORT void
method_exchangeImplementations(Method _Nonnull m1, Method _Nonnull m2)
OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

以上为苹果runtime中提供的API,相信大家看下注释就知道怎么使用了,举个例子说明更加让人清晰!.(例子来源于编写高质量ios与OS X代码的52个有效方法书本中)

1.没有做交换前
 //方法交换前
    
    NSString *tesString = @"Thls ].S tHe StRiNg";
    
    NSLog(@"<============ 交换之前 ============>");
    NSString *lowercaseString_before = [tesString lowercaseString];//全部转为小写
    NSLog(@"lowercaseString = %@",lowercaseString_before);
    // Output: lowercaseString = THIS IS THE STRING
    NSString *uppercaseString_before = [tesString uppercaseString];//全部转为大写
    NSLog(@"uppercaseString = %@",uppercaseString_before);
    NSLog(@"====================");
2.交换后
/*
 方法交换后
   此函数的两个参数表示待交换的两个方法实现,
   void method_exchangeimplementations(Method ml, Method m2J
 
 而方法实现则可通过下列函数获得:
  Method class_getinstanceMethod(Class aClass, SEL aSelector)
  */
    
    Method originalMethod = class_getInstanceMethod([NSString class], @selector(lowercaseString));
    
    Method swappedMethod = class_getInstanceMethod([NSString class], @selector(uppercaseString));
    
   //交换方法  
    method_exchangeImplementations(originalMethod, swappedMethod);
    
    NSLog(@"<============ 交换之后 ============>");
    
    NSString *lowercaseString_after = [tesString lowercaseString];
    NSLog(@"lowercaseString = %@",lowercaseString_after);
          // Output: lowercaseString = THIS IS THE STRING
    NSString *uppercaseString_after = [tesString uppercaseString];
    NSLog(@"uppercaseString = %@",uppercaseString_after);
    
举报

相关推荐

0 条评论