簡介
最近在初始化類的時候框都,會有很多沒有返回值的初始化方法需要調(diào)用,每次都需要再寫一遍呵晨,所以想把函數(shù)裝進 NSArray 中可以自動調(diào)用魏保。結(jié)果查了一下真的可以,所以做個筆記記一下
- (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);
}];