动态方法
2017-02-10 本文已影响3人
Jinfei_Chen
相信大家都见过或用过
NSSelectorFromString
与 [NSObject performSelector:]
[ 常见的使用场景 ] :
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 0) {
[self func0];
} else if (indexPath.row == 1) {
[self func1];
} else if (indexPath.row == N) {
[self funcN];
} else {
[self doSomething];
}
}
那这个可以用动态方法怎么做重构呢?
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
SEL funcSEL = NSSelectorFromString([NSString stringWithFormat:@"func%d", indexPath.row]);
if ([self respondsToSelector:funcSEL]) {
[self performSelector:funcSEL];
} else {
[self dosomething];
}
}