ios runtime之方法交换

   苹果的文档一直是以人性化著称,今天没事看了看<objc/runtime.h>中的API,感觉人家确实写的好,自己也顺便做下记录。

/**
 * 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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值