【iOS】Class对构造简洁代码很有帮助
(这到底取的是什么标题啊)
首先先看这段代码(有删减)
@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 ; } }
看,很方便吧!
本文来自博客园,作者:MrYu4,转载请注明原文链接:https://www.cnblogs.com/MrYU4/p/15778885.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了