• 除了判断语句if switch 我们还可以怎么做?-b


      之前项目中有根据后台数据执行不同代码,根据不同的字符串返回不同UIViewController对象,最开始需要的vc 种类不多我用的是if else 做字符串比较再执行不同代码,但是如果需求的vc 有几十个,需要的恰好是最后一个呢?这样if else if 代码看起来混乱并且消耗资源。

     其实我们可以有两种方法解决类似的判断问题,

    1,使用注册机制。

    2,直接使用网络中的字符串调用方法。

    一,注册机制,我们只需要把代码通过相应的字符串放入字典中,根据字符串取出相应的代码运行得到结果,iOS中我们直接使block 存储相应代码。如下通过过for循环把不通的vc放入字典,

    _dic=[[NSMutableDictionaryalloc]initWithCapacity:_arr.count];

    for(int i =0; i <_arr.count; i++) {

    NSString*key = [NSString  stringWithFormat:@"%d",i];

    UIViewController* (^block)()= ^(){

    NSLog(@"这是第%d个",i);

    UIViewController*viewc = [[UIViewController alloc] init];

    viewc.view.backgroundColor= [UIColor colorWithRed:arc4random()%5/5.0 green:arc4random()%5/5.0 blue:arc4random()%5/5.0 alpha:1];

    return viewc;

    };

    [_dic setObject:block forKey:key];

    }

    使用的时候这样,取出block 运行block的到相应的vc 

    -(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{

    UIViewController* (^getblock)() = [_dic objectForKey:[NSString stringWithFormat:@"%d",indexPath.row]];

    UIViewController*vc =getblock();

    [self.navigationControllerpushViewController:vcanimated:YES];

    二,直接通过字符串直接调用相应的方法,不过首先是要和后台商量好格式。

    //indexStr :是后台数据,用来判断执行的字符串。

    NSString*selectStr = [indexStr stringByReplacingOccurrencesOfString:@"/"withString:@"_"];//替换使方法名合法

    SEL select = NSSelectorFromString(selectStr) ;

    if([self respondsToSelector:select]) {

    UIViewController*vc = [self performSelector:select];

    return vc;

    }  

    例如后台字符串传来的是“shop/brand”,那么只需要添加方法

    -(UIViewController*)shop_brand{

    UIViewController*vc = [[UIViewController alloc]init];

    NSLog(@"shop_brand");

    return vc;

    }

    我们项目中使用的是第二种方法,个人觉得这样对性能和代码整洁有很大的帮助,有错误或者不妥的地方也欢迎指正。



    文/哈尔湖(简书作者)
    原文链接:http://www.jianshu.com/p/e51c6af6025c
    著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
  • 相关阅读:
    [Swift]LeetCode380. 常数时间插入、删除和获取随机元素 | Insert Delete GetRandom O(1)
    [Swift]LeetCode378. 有序矩阵中第K小的元素 | Kth Smallest Element in a Sorted Matrix
    说说心声------ 一些经历
    安装eclipse maven插件m2eclipse No repository found containing
    苹果浏览器实战(三)
    CSDN挑战编程——《绝对值最小》
    高可用技术工具包 High Availability Toolkit
    jstl 标签 循环 序号
    坚向的ViewPager,上下滑动的组件,android上下滑动 VerticalPager
    Php socket数据编码
  • 原文地址:https://www.cnblogs.com/isItOk/p/5754999.html
Copyright © 2020-2023  润新知