Silver Challenge - NSDictionary


#1

So I managed to produce a working solution for this silver challenge. However I suspect that I might have written code that’s incosistent with Objective-C conventions / style. I would appreciate to have some feedback for it.

First thing is instead of using switch or case statements I used an NSDictionary where my colorNames array matches to the colors array.

[code]- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
if (self) {
[self setColors:[NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], nil]];
[self setColorNames:[NSArray arrayWithObjects:@“Red”, @“Green”, @“Blue”, nil]];
[self setColorDict:[[NSDictionary alloc] initWithObjects:[self colors] forKeys:[self colorNames]]];
// Get the tab bar item
UITabBarItem *tbi = [self tabBarItem];

    // Give it a label
    [tbi setTitle:@"Hypnosis"];
    
    // Create a UI image from a file
    // This will use Hypno@2x.png on retina display devices
    UIImage *i = [UIImage imageNamed:@"Hypno.png"];
    
    // Put that image on the tab bar item
    [tbi setImage:i];
}
return self;

}[/code]

And then in the viewDidLoad method I wrote the following code:

[code]- (void)viewDidLoad
{
[super viewDidLoad];

// Init and add the segmented control
self.colorChooser = [[UISegmentedControl alloc] initWithItems:[self colorNames]];
[[self colorChooser] setSegmentedControlStyle:UISegmentedControlStylePlain];
[[self colorChooser] setCenter:self.view.center];
[[self view] addSubview:[self colorChooser]];

[[self colorChooser] addTarget:self action:@selector(changeCircleColor) forControlEvents:UIControlEventValueChanged];

NSLog(@"HypnosisViewController loaded its view.");

}[/code]

And my changeCircleColor method is as follows (I don’t understand why I had to declare a new HypnosisView instant again, when I tried to send the message directly to [self view] I got an error saying “No visible @interface declares selector setCircleColor”)

-(void)changeCircleColor { HypnosisView *myView = [self view]; [myView setCircleColor:[self colorDict][[[self colorChooser] titleForSegmentAtIndex:[self.colorChooser selectedSegmentIndex]]]]; }

Well, even though this approach works as I want it to, what concerns me is that I had to initialise the UISegmentedControl programmatically, since I couldn’t figure out how to combine a XIB file and my HypnosisView. This was not an approach explained in the book so I had to find a solution myself, which in this case does not look healthy. And another thing is the ugly way I got the selected segment title: [[self colorChooser] titleForSegmentAtIndex:[self.colorChooser selectedSegmentIndex]] Is there a way to do this more neatly?

I would appreciate comments both on these issues and other things you find.

Thanks!