Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Build a Simple iPhone App with Objective-C Improving Our User Interface Adding a Pop of Color

Jacek Gałka
Jacek Gałka
8,044 Points

Using NSDictionary instead of NSArray


I've tried to create NSDictionary instead of NSArray to store different colors for my app. I also create a method with UIColor return type (just like Pasan did) and one parameter of type NSString but without using arc4random.

  • (instancetype)init { self = [super init]; if (self) { _kolory = [[NSDictionary alloc]initWithObjectsAndKeys: @[[UIColor colorWithRed:222/255.0 green:171/255.0 blue:66/255.0 alpha:1.0]], @"Tło", @[[UIColor colorWithRed:85/255.0 green:176/255.0 blue:112/255.0 alpha:1.0]], @"Wygrana", @[[UIColor colorWithRed:223/255.0 green:171/255.0 blue:66/255.0 alpha:1.0]], @"Przegrana", nil]; } return self; }

  • (UIColor *)wyborKoloruDlaElementu: (NSString *)element { return [self.kolory objectForKey:element]; }

My goal is to change background color by calling a method with an argument of type NSString that match a key in my NSDictionary. self.view.backgroundColor = [self.koloryElementow wyborKoloruDlaElementu:@"Tło"];

When i try to run the app with calling the method - return UIApplicationMain(argh, argue, nil, NSStringFromClass([AppDelegate class])); Thread1: signal SIGABRT

Where is the problem? Thanks in advance for your help!

1 Answer

Let's examine the objects you inserted into your dictionary: @"Tło": @[[UIColor colorWithRed:222/255.0 green:171/255.0 blue:66/255.0 alpha:1.0]]

For the values of your dictionary, [UIColor colorWithRed:green:blue:alpha:] creates a UIColor object, while wrapping that into @[ .... ] actually creates an NSArray that contains that object.

So when you try to retrieve that object later with [self.kolory objectForKey:element] (or with a more modern syntax: self.kolory[element]), you actually obtained an NSArray contain a single UIColor instead of just a UIColor. From there you probably sent that object (again, NSArray containing a UIColor) to something that was expecting just a UIColor.

Jacek Gałka
Jacek Gałka
8,044 Points

I messed up with syntax here! I just don't know why I couldn't figure it out by myself. Everything works now! Thank's for your time.