Ways to replace massive if statement with alternative construct in Objective-C

后端 未结 2 1448
Happy的楠姐
Happy的楠姐 2020-12-18 06:58

I have a fairly lengthy if statement. The if statement examines a string \"type\" to determine what type of object should be instantiated. Here\'s a sample...

<         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-18 07:21

    You can use an NSDictionary filled with ObjC 'Blocks' to do a switch-like statement which executes the desired code. So make a dictionary with your string keys mapped to a block of code to execute when each is found:

    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          ^{ NSLog(@"found key1"); }, @"key1", 
                          ^{ NSLog(@"found key2"); }, @"key2", 
                          nil];
    

    You'll probably prepare this dictionary only once at some early stage like in a constructor or a static initializer so that it is ready when your later code executes.

    Then instead of your if/else block, slice out the string key from whatever intput you are receiving (or maybe you won't need to slice it, whatever):

    NSString *input = ...
    NSRange range = ...
    NSString *key = [input substringWithRange:range]; 
    

    And do the (fast) dictionary lookup for the code to execute. Then execute:

    void (^myBlock)(void) = [dict objectForKey:key];
    myBlock();
    

提交回复
热议问题