QuickTip: Sort an NSArray of Objects

Say we have an NSArray named employees which contains Employee objects. The Employee object has a property named startDate. We can very easily sort this array by the start date using an NSSortDescriptor.

First we create the sort descriptor, assign it a key in which to sort on, and specify how we would like the array sorted.

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"startDate" ascending:YES];

Now we create a new sorted array from the employees array using the sortedArrayUsingDescriptors: method. This method accepts an array of sort descriptors.

NSArray *sortedEmployees = [employees sortedArrayUsingDescriptors:@[sortDescriptor]];

 
With the introduction of blocks in iOS 4 and Mac OS 10.6, we can do this same task slightly different.

NSArray *sortedEmployees = [employees sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    NSDate *firstDate = [(Employee *)a startDate];
    NSDate *secondDate = [(Employee *)b startDate];
    return [firstDate compare:secondDate];
}];

 
Apple’s documentation on NSSortDescriptor
Apple’s documentation on NSArray


Print This Post Print This Post

QuickTip: Finding which NSDate is older

I recently did some date comparison with one of the apps I’m working on. Checking to see which date is older (or newer) isn’t very straightforward in Objective-C. This post is intended to help anyone struggling with this.

First we have two dates:

NSDate *date1 = [NSDate date];
NSDate *date2 = [NSDate date];

Next to determine which date is older we will use the compare method on our two dates. This will return an NSComparisonResult value, so we need to check to see what it is. If it is equal to NSOrderedAscending, then we know the first date is the older date.

if ([date1 compare:date2] == NSOrderedAscending) {
    // date1 comes before date2
}

The possible values that could be returned by the compare: method are: NSOrderedAscending, NSOrderedDescending, and NSOrderedSame. To read more on NSDate, here is a link to Apple’s documentation.


Print This Post Print This Post

Cocos2D Podcast

The Cocos2D Podcast is a great resource if you are interested in industry leading developers and what they are doing. I listen to it regularly, and was surprised and honored when Azam asked me to be a guest on the show to talk about Augmented Reality. This past Saturday we recorded the show, and yesterday it became available. Thank you Azam and Steffen for having me on!

Check it out!
http://cocos2dpodcast.wordpress.com/2011/12/06/augmented-reality-with-nick-waynik/


Print This Post Print This Post

QuickTip: Navigation Bar Image Fix in iOS 5

When working on a project, it was brought to my attention that the app’s custom navigation bar image wasn’t displaying. After looking at the code, the previous developer was using the drawRect: method to set the image. This no longer works in iOS 5 because the method never gets called, unless you subclass UINavigationBar. Below is a snippet of code to get the image to display on iOS 5 devices.

*UPDATE: Use run-time checking!*

float version = [[[UIDevice currentDevice] systemVersion] floatValue];
if (version >= 5.0) {
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"portrait_image.png"] forBarMetrics: UIBarMetricsDefault];
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"landscape_image.png"] forBarMetrics:UIBarMetricsLandscapePhone];
    [[UIBarButtonItem appearance] setTintColor:[UIColor colorWithRed:201.0/255 green:31.0/255 blue:56.0/255 alpha:1]];
}

Print This Post Print This Post

QuickTip: NSUserDefaults

Just about every app that I work on utilizes NSUserDefaults in one way or another. It is quick to implement and very easy to use.

First you need to create an NSUserDefaults variable:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

Next you will need to save something that can be accessed at another time. This is very easy, we will use set methods to set values for keys. The keys can be named whatever you like, I named mine based on what object type I’m saving for this demo. Here we will save quite a few different object types:

// NSString
[userDefaults setObject:@"Your text here" forKey:@"StringKey"];

// Float
[userDefaults setFloat:5.22 forKey:@"FloatKey"];

// Double
[userDefaults setDouble:6.1234 forKey:@"DoubleKey"];

// NSInteger
[userDefaults setInteger:7 forKey:@"IntegerKey"];

// Boolean
[userDefaults setBool:YES forKey:@"BooleanKey"];

 

After saving objects to your NSUserDefaults, you will want to run the the synchronize method.

[userDefaults synchronize];

 

Next up we will retrieve values for the keys we saved above. Here we will get the object type for the keys we specified above and assign it to a variable.

// NSString
NSString *myString = [userDefaults stringForKey:@"keyToLookupString"];

// Float
float myFloat = [userDefaults floatForKey:@"floatKey"];

// Double
double myDouble = [userDefaults doubleForKey:@"DoubleKey"];

// NSInteger
NSInteger myInteger = [userDefaults integerForKey:@"integerKey"];

// Boolean
BOOL myBoolean = [userDefaults boolForKey:@"BooleanKey"];

And that is it! Hope you enjoyed this Quick Tip.


Print This Post Print This Post

Quick Tip: Fix clear button for Calculator

I upgraded to Mac OS X Lion last month and there has been quite a few changes to get used to. One thing I noticed was that my clear key on the full keyboard doesn’t work anymore in the Calculator widget. After a little searching, I found a solution!

1. Open up a finder window and navigate to the following folder:

/Library/Widgets

2. Next locate Calculator.wdgt and ctrl-click on it, then select “Show Package Contents.”
3. Copy Calculator.js to some other location such as your desktop.
4. Open the file up in any text editor.
5. Goto line 127, and change “case 63289? to “case 61705?. It should look like this when you are done.

case 61705:
case 27:
	key = "c";
	break;

6. Close and save the file.
7. Copy the file back to the contents of Calculator.wdgt.
8. Fire up dashboard and remove your current calculator widget and add a new one.

You’re clear button will now work in Calculator!

Here is the link to the original solution.


Print This Post Print This Post

Quick Tip: Show Library Folder in Lion

I use my user library folder all the time, and I’m a little bit annoyed that the Library folder is now hidden in Mac OS X Lion. Here is how I changed that!

Open up Terminal and type the following and tap return:

chflags nohidden /users/<insert your username here>/Library

Note: Make sure you substitute your username in that command.


Print This Post Print This Post

Quick Tip: NSDictionary Contents

I have been doing some work with JSON recently and it can be very difficult to wade through the results. This snippet of code can very easily show you keys and values for objects within a NSDictionary.

NSString *key;
for(key in jsonDictionary){
     NSLog(@"Key: %@, Value %@", key, [jsonDictionary objectForKey: key]);
}

I hope this helps out!


Print This Post Print This Post

Quick Tip: Changing a Sprite Image in Cocos2D

Have you ever wanted to change or swap out an image assigned to a sprite?  Well, it’s very easy to do!

We will start out by adding a Sprite Batch Node to the a layer, then we will add a new sprite.

// Add Sprite Batch Node
CCSpriteBatchNode *batchNode = [CCSpriteBatchNode batchNodeWithFile:@"Sprites.pvr.ccz"];
[self addChild:batchNode];
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"Sprites.plist"];

// Add new sprite
CCSprite *sprite1 = [CCSprite spriteWithSpriteFrameName:@"SpriteName0.png"];
sprite1.position = ccp(240,160);
[self addChild:sprite1];

All we need to do to change the image used by the sprite is to set it’s display frame like so:

[sprite1 setDisplayFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"SpriteName1.png"]];

And that’s a wrap! I hope you enjoyed this quick tip, and I will be adding one a week. If you have any suggestions, please add them in the comments section.


Print This Post Print This Post

Cocoaheads Pittsburgh

Here is the pdf version of the slides and a zip of the project.

Intro To Cocos2D Slides

TestApp Project


Print This Post Print This Post