简介
最近在初始化类的时候,会有很多没有返回值的初始化方法需要调用,每次都需要再写一遍,所以想把函数装进 NSArray 中可以自动调用。结果查了一下真的可以,所以做个笔记记一下
- (void)viewDidLoad {
[super viewDidLoad];
NSString* A = NSStringFromSelector(@selector(loadA));
NSString* B = NSStringFromSelector(@selector(loadB));
NSString* C = NSStringFromSelector(@selector(loadC));
NSArray *arr = @[A,B,C];
[arr enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSString *selector = obj;
if (!self) { return; }
SEL performSelector = NSSelectorFromString(selector);
if ([self respondsToSelector:performSelector]){
[self performSelector:performSelector];
}
}];
}
- (void)loadA{
NSLog(@"call load A +++++++");
}
- (void)loadB{
NSLog(@"call load B ++++++++");
}
- (void)loadC{
NSLog(@"call load C +++++");
}
然后就写了一个小 demo,写完后报了警告,查过爆栈热门 iOS 问题后,解决了这个问题。
NSString* A = NSStringFromSelector(@selector(loadA));
NSString* B = NSStringFromSelector(@selector(loadB));
NSString* C = NSStringFromSelector(@selector(loadC));
NSArray *arr = @[A,B,C];
[arr enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSString *selector = obj;
if (!self) { return; }
SEL performSelector = NSSelectorFromString(selector);
IMP imp = [self methodForSelector:performSelector];
void (*func)(id, SEL) = (void *)imp;
func(self, performSelector);
}];