(这到底取的是什么标题啊)
首先先看这段代码(有删减)
@property (nonatomic, copy)NSMutableArray <NSMutableArray *>*datas;
- (void)viewDidLoad {
NSMutableArray *section0 = @[
@{@"title" : @"我的借阅",
@"leftIcon" : @"my_borrow",
@"vc" : @"ManageBooksViewController"}.mutableCopy,
@{@"title" : @"我的书籍",
@"leftIcon" : @"my_book",
@"vc" : @"MyFileViewController"}.mutableCopy,
].mutableCopy
...
self.datas = @[section0,section1,section2, section3].mutableCopy;
}
#pragma mark 选择事件
- (void) tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger row = indexPath.row;
NSInteger section = indexPath.section;
NSString *vcStr = self.datas[section][row][@"vc"];
if ([vcStr isEqualToString:@"MineIntroductionViewController"]) {
ActivityWebViewController *vc = [[ActivityWebViewController alloc]initWithContentUrl:@"http://librarymanager.30days-tech.com/h5/introduce.html"
title:@"使用说明"
presenting:NO];
vc.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:vc
animated:YES];
}
if ([vcStr isEqualToString:@"MyFileViewController"]) {
ManageBooksViewController *vc = [[ManageBooksViewController alloc]init];
vc.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:vc
animated:YES];
} else if ([vcStr isEqualToString:@"MyBooksViewController"]) {
MyFileViewController *vc = [[MyFileViewController alloc]init];
vc.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:vc
animated:YES];
} else if ([vcStr isEqualToString:@"MyMoreSettingViewController"]) {
MyMoreSettingViewController *vc = [[MyMoreSettingViewController alloc]init];
vc.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:vc
animated:YES];
}
.......
}
着看之下貌似没什么问题,语法也说得过去,而且总比用indexPath来判断进入哪个控制器要简单得多,后期修改也不存在太大的问题,但随着需求的增加我们会发现每多出一个控制器,push控制器代码又会多出一段:
XXX *vc = [[XXX alloc]init];
vc.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:vc
animated:YES];
so,利用Class就可以瞬间把代码缩减好了。
#pragma mark 选择事件
- (void) tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger row = indexPath.row;
NSInteger section = indexPath.section;
NSString *vcStr = self.datas[section][row][@"vc"];
Class vcClass = NSClassFromString(vcStr) ;
if (vcClass) {
UIViewController *vc = [[vcClass alloc]init];
vc.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:vc
animated:YES];
return ;
}
}
看,很方便吧!