runtime----獲取屬性,方法,成員變量,協(xié)議

      unsigned int count;
      //獲取屬性列表
      objc_property_t *propertyList = class_copyPropertyList([Son class], &count); 
    for (unsigned int i=0; i<count; i++) {
        const char *propertyName = property_getName(propertyList[i]);
        NSLog(@"property---->%@", [NSString stringWithUTF8String:propertyName]);
    }  
 unsigned int count;
 //獲取方法列表
    Method *methodList = class_copyMethodList([Son class], &count);
    for (unsigned int i = 0; i<count ; i++) {
        Method method = methodList[i];
        NSLog(@"method---->%@", NSStringFromSelector(method_getName(method)));
    }
  unsigned int count;
//獲取成員變量列表
    Ivar *ivarList = class_copyIvarList([Son class], &count);
    for (unsigned int i = 0; i<count; i++) {
        Ivar myIvar = ivarList[i];
        const char *ivarName = ivar_getName(myIvar);
        NSLog(@"Ivar---->%@", [NSString stringWithUTF8String:ivarName]);
    }
  unsigned int count;
   //獲取協(xié)議列表
    __unsafe_unretained Protocol **protocolList = class_copyProtocolList([Son class], &count);
    for (unsigned int i = 0 ; i<count; i++) {
        Protocol *myProtocal = protocolList[i];
        const char *protocolName = protocol_getName(myProtocal);
        NSLog(@"protocol---->%@", [NSString stringWithUTF8String:protocolName]);
    }
//方法交換
- (void)exchangeMethod {
    //獲得viewController的生命周期方法的selector
    SEL systemSel = @selector(run);
    //自己實(shí)現(xiàn)的將要被交換的方法的selector
    SEL mySel = @selector(noRun);
    //兩個(gè)方法的Method
    Method systemMethod = class_getInstanceMethod([self class], systemSel);
    Method myMethod = class_getInstanceMethod([self class], mySel);
    
    //首先動(dòng)態(tài)添加方法,實(shí)現(xiàn)是被交換的方法,返回值表示添加成功還是失敗
    BOOL isAdd = class_addMethod([Son class], systemSel, method_getImplementation(myMethod), method_getTypeEncoding(myMethod));
    if (isAdd) {
        //如果成功,說明類中不存在這個(gè)方法的實(shí)現(xiàn)
        //將被交換方法的實(shí)現(xiàn)替換到這個(gè)并不存在的實(shí)現(xiàn)
        class_replaceMethod([Son class], mySel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
    }else{
        //否則,交換兩個(gè)方法的實(shí)現(xiàn)
        method_exchangeImplementations(systemMethod, myMethod);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容