美文网首页
iOS - Runtime method_exchangeImp

iOS - Runtime method_exchangeImp

作者: 码代码的小马 | 来源:发表于2021-05-14 10:02 被阅读0次

Runtime源码下载

1. 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);

2. 源码

void method_exchangeImplementations(Method m1, Method m2)
{
   if (!m1  ||  !m2) return;

   mutex_locker_t lock(runtimeLock);

   IMP imp1 = m1->imp(false);
   IMP imp2 = m2->imp(false);
   SEL sel1 = m1->name();
   SEL sel2 = m2->name();

   m1->setImp(imp2);
   m2->setImp(imp1);


   // RR/AWZ updates are slow because class is unknown
   // Cache updates are slow because class is unknown
   // fixme build list of classes whose Methods are known externally?

   flushCaches(nil, __func__, [sel1, sel2, imp1, imp2](Class c){
       return c->cache.shouldFlush(sel1, imp1) || c->cache.shouldFlush(sel2, imp2);
   });

   adjustCustomFlagsForMethodChange(nil, m1);
   adjustCustomFlagsForMethodChange(nil, m2);
}

相关文章

网友评论

      本文标题:iOS - Runtime method_exchangeImp

      本文链接:https://www.haomeiwen.com/subject/spdodltx.html