工作中生成的静态库程序中为了避免必须要导入头文件,很多时候需要动态加载,减少导入头文件的累赘,动态加载类方法和动态加载实例方法成了必然。
@interface Person : NSObject
+(void)personClick;
+(void)personClickWithSingSong:(NSString*)singSong;
+(void)eatAnimal:(NSString*)animal andHongShao:(NSString*)hongShao andYundong:(NSString*)yundong;
+ (instancetype)sharePersonManager;
-(void)haveFlowerWithWhite:(NSString*)white andRed:(NSString*)red andOrange:(NSString*)orange;
@end
+(void)eatAnimal:(NSString*)animal andHongShao:(NSString*)hongShao andYundong:(NSString*)yundong
{
NSLog(@"吃小动物%@==%@==%@",animal,hongShao,yundong);
}
-(void)haveFlowerWithWhite:(NSString*)white andRed:(NSString*)red andOrange:(NSString*)orange
{
NSLog(@"实例方法==%@==%@==%@",white,red,orange);
}
+(void)personClick
{
NSLog(@"类方法");
}
+(void)personClickWithSingSong:(NSString*)singSong
{
NSLog(@"类方法有一个参数的%@",singSong);
}
static id personManager = nil;
+ (instancetype)sharePersonManager {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if(personManager == nil){
personManager = [[self alloc] init];
}
});
return personManager;
}
-(void)eatWahaha
{
NSLog(@"喝娃哈哈");
}
以下调用方式
1.无参数或者参数少于两个(用这种相对方便)
//无参数的情况
Class personClass = NSClassFromString(@"Person");
[[personClass class] performSelector:@selector(personClick)];
//有一个参数
Class personClass = NSClassFromString(@"Person");
[[personClass class] performSelector:@selector(personClickWithSingSong:) withObject:@"云与海"];
2021-06-07 14:40:30.248390+0800 RuntimeDemo[6126:547111] 类方法有一个参数的云与海
2.两个参数以上(动态调用类方法 || 动态调用实例方法)
//动态调用类方法
Class personClass = NSClassFromString(@"Person");
NSString *strA = @"字符串objc_msgSend";
NSString *strB = @"字符串objc_msgSend";
NSString *strC = @"字符串objc_msgSend";
SEL selggg = NSSelectorFromString(@"eatAnimal:andHongShao:andYundong:");
((void (*) (id, SEL, NSString *, NSString *, NSString *)) objc_msgSend) (personClass, selggg, strA, strB, strC);
2021-06-07 14:43:35.524104+0800 RuntimeDemo[6145:548656] 吃小动物字符串objc_msgSend==字符串objc_msgSend==字符串objc_msgSend
//动态调用实例方法
Class personClass = NSClassFromString(@"Person");
NSString *strA = @"字符串objc_msgSend";
NSString *strB = @"字符串objc_msgSend";
NSString *strC = @"字符串objc_msgSend";
SEL selggg = NSSelectorFromString(@"haveFlowerWithWhite:andRed:andOrange:");
((void (*) (id, SEL, NSString *, NSString *, NSString *)) objc_msgSend) ([personClass performSelector:@selector(sharePersonManager)], selggg, strA, strB, strC);
2021-06-07 14:47:35.530893+0800 RuntimeDemo[6170:551003] 实例方法==字符串objc_msgSend==字符串objc_msgSend==字符串objc_msgSend
/*************************第二种方式**************************/
//也可以NSObject写个分类
Class personClass = NSClassFromString(@"Person");
NSString *strA = @"字符串objc_msgSend";
NSString *strB = @"字符串objc_msgSend";
NSString *strC = @"字符串objc_msgSend";
[[personClass performSelector:@selector(sharePersonManager)] performSelector:@selector(haveFlowerWithWhite:andRed:andOrange:) withObjects:@[strA,strB,strC]];
分类下载地址
链接: https://pan.baidu.com/s/1qXk6JY7hN8wWJZqONUEqHA 密码: dn1s
网友评论