Using an NSDictionary as an argument to a method.

I have a series of animated scenes that I am adding as rewards to my apps. The animation takes place on three layers at the moment, but I keep adding layers and every time I do that I have to change my method definition and all the method calls. I decided to put all my arguments into an NSDictionary so that I don’t have to keep changing the method.

This is the original code.


NSInteger numRewards = 10;
NSInteger randomReward = arc4random() % numRewards;

if (randomReward == 0 ) {
    UIColor *backgroundColor = [UIColor colorWithRed:102/255.0 green:204/255.0 blue:255/255.0 alpha:1];
    [self animatedReward:@"Boat"
     withForegroundCount:4
    withMovingPartsCount:6
     withBackgroundColor:backgroundColor];
}

Every time I add a layer I need to change the method. And all the method calls. By making it an NSDictionary, I can play around with layers, and anything else I want to add, without having to change the method each time.


NSInteger numRewards = 10;
NSInteger randomReward = arc4random() % numRewards;

if (randomReward == 0 ) {
    UIColor *backgroundColor = [UIColor colorWithRed:102/255.0 green:204/255.0 blue:255/255.0 alpha:1];
    NSDictionary *partsCounts = [NSDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithInt:4],@"foreground",
                                 [NSNumber numberWithInt:3],@"moving", nil];
    NSLog(@"Parts counts%i",partsCount);
    [self animatedReward:@"Boat"
             partsCounts:partsCounts
     withBackgroundColor:backgroundColor];
}

The method is declared as:


- (void)animatedReward:(NSString *)scene
           partsCounts:(NSDictionary)partsCounts
   withBackgroundColor:(UIColor *)backgroundColor;

Notice that the number of images in each layer are stored as NSNumbers in the dictionary. That’s because NSIntegers aren’t objects. To get the integers back out of the dictionary, you use this line.


    NSInteger foregroundCount = [[partsCounts objectForKey:@"foreground"]  integerValue];

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.