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

后端 未结 2 1450
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:07

    The dictionary approach would be easily doable. Assuming the various managers have been boiled down to specific instances when you create the dictionary, it'd be just the same as almost any object-oriented language:

    NSDictionary *stringsToManagers = 
        [NSDictionary dictionaryWithObjectsAndKeys:
             @"coin-large", gameLayer.coinLargeMgr,
             @"coin-small", gameLayer.coinSmallMgr,
             nil];
    
    // this is assuming that type may contain multiple types; otherwise
    // just use [stringsToManagers objectForKey:string]
    for(NSString *string in [stringsToManagers allKeys])
    {
        if([type rangeOfString:string].location != NSNotFound)
        {
             [[stringsToManagers objectForKey:string] addNewObject];
             // or get it and store it wherever it should go
        }
    }
    

    If all the managers do is vend appropriate objects, the more object-oriented approach might be:

    NSDictionary *stringsToClasses = 
        [NSDictionary dictionaryWithObjectsAndKeys:
             @"coin-large", [LargeCoin class],
             @"coin-small", [SmallCoin class],
             nil];
    
    // this is assuming that type may contain multiple types; otherwise
    // just use [stringsToManagers objectForKey:string]
    for(NSString *string in [stringsToManagers allKeys])
    {
        if([type rangeOfString:string].location != NSNotFound)
        {
             id class = [stringsToManagers objectForKey:string];
    
             id newObject = [[class alloc] init];
             // this is exactly the same as if, for example, you'd
             // called [[LargeCoin alloc] init] after detecting coin-large
             // within the input string; you should obviously do something
             // with newObject now
        }
    }
    

    That could save you having to write any managers if your program structure otherwise fits.

提交回复
热议问题