iOS運行時使用(動態添加方法)


1 舉例  我們實現一個Person類 然后Person 其實是沒得對象方法eat:的

下面調用person的eat方法 程序是會奔潰的 那么需要借助運行時動態的添加方法

Person *p = [[Person alloc]init];
    [p performSelector:@selector(eat:) withObject:@"雞腿"];

在perosn.m文件中進行實現運行時動態添加方法

//
//  Person.m
//  運行時(動態添加方法)
//
//  Created by ALD on 2018/6/4.
//  Copyright © 2018年 ALD. All rights reserved.
//

#import "Person.h"
#import <objc/message.h>
@implementation Person
//使用到了未定義的類方法
//+(BOOL)resolveClassMethod:(SEL)sel{
//
//}

// 定義eat 方法 默認會前面兩個隱式參數 id self, SEL _cmd  第三個才是我們自己傳入的參數
void eat(id self, SEL _cmd ,id object ){
    NSLog(@"吃了%@", object);
}
//使用到了未定義的對象方法
+(BOOL)resolveInstanceMethod:(SEL)sel{
    NSLog(@"%@", NSStringFromSelector(sel));
    if (sel  == @selector(eat:)) {
        //動態添加方法
        
        /**
         <#Description#>

         @param cls#> 那個類 description#>
         @param name#> 方法名 description#>
         @param imp#> 方法指針 description#>
         @param types#> 方法類型 description#>
         @return <#return value description#>
         */
//        class_addMethod(<#Class  _Nullable __unsafe_unretained cls#>, <#SEL  _Nonnull name#>, <#IMP  _Nonnull imp#>, <#const char * _Nullable types#>)
        class_addMethod([self class], @selector(eat:), (IMP)eat, "v");
    }
    return [super resolveInstanceMethod:sel];
    
}
@end

對 class_addMethod  不太理解里面參數含義可以去文檔查詢 拷貝 shift + command + 0 然后搜索你想查的方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM