How to Format an NSString

Dec 19, 2009   //   by Derek van Vliet   //   Development  //  2 Comments

It’s back to basics with today’s advent tip. I would be surprised if anything short of ALL developers have had a need to format strings at one time or another. iPhone app development is no exception.

String formatting allows you to build a string based on a template and varying types of values. For example, if I am keeping track of a player’s score as an integer and I want to display a string to the player that celebrates their score by saying “You scored 2600! Way to go!”, then I need string formatting to get the correct score in the middle of that string.

How to Do It

Below is an example of how to build the above NSString. This example formats a string with an integer in it using the %i format specifier.

int score = 2600;
NSString * scoreString = [NSString stringWithFormat:@"You scored %i! Way to go!",score];

Format Specifiers

But string formatting doesn’t stop at putting integers in strings. Below are some of the most common format specifiers for other value types:

Specifier Purpose
%i integer
%f float
%@ Objective-C object (commonly used to specify another NSString)
%x hexadecimal

How to Take the Shine off Your App’s Icon

Dec 18, 2009   //   by Derek van Vliet   //   Development  //  1 Comment

Screen shot 2009-12-18 at 4.56.39 PMiPhone apps have a curved shine applied to their icons by default. It makes any icon look like it has been buffed to a high gloss. But what if you don’t want your icon to look shiny? What if you want full control over the look of your icon? Don’t fret: there are a couple of easy ways to disable the shine and take back control, and they’re both rather easy.

UIPrerenderedIcon

Screen shot 2009-12-18 at 4.45.15 PMThe first method is to add a setting to your project in Xcode. Just follow these 4 simple steps to do so:

1. Open your iPhone app’s info.plist file.

2. Command-click and select Add Row.

3. Select “Icon already includes gloss and bevel effects” from the drop down that appears.

4. Check the checkbox that appears next to the new row.

Alternately, you could set this setting in your info.plist by editing it in a text editor. You just need to add the following 2 XML tags inside the <dict> tag:

<dict>
	<key>UIPrerenderedIcon</key>
	<true/>
	...

How to Prevent the iPhone from Sleeping

Dec 17, 2009   //   by Derek van Vliet   //   Development  //  No Comments

put-the-iphone-to-sleep

Left idle, the iPhone goes into sleep mode after about a minute. This narcoleptic behaviour saves on battery life, but there are situations where you would not want the device to go to sleep. For instance, in the middle of a multiplayer game that is turn-based, such as chess. You could wait for longer than a minute for your opponent to make make their move and you wouldn’t want to miss it when they did.

To keep the iPhone awake and alert, simply run the following line of code:

[UIApplication sharedApplication].idleTimerDisabled = YES;

Do use this tip sparingly though. The iPhone’s power is unmatched, to be sure, but unfortunately it is not unlimited.

How to Show the Network Activity Indicator

Dec 16, 2009   //   by Derek van Vliet   //   Uncategorized  //  1 Comment

Screen shot 2009-12-16 at 10.14.26 PMThe network activity indicator is like the UIActivityIndicatorView we previously discussed, only it sits on the status bar, it is smaller, and believe it or not, it is even easier to manipulate. It’s the little rotating wheel of bars (pictured right) that shows up on the status bar whenever your iPhone is accessing the network.

Show It

If you would like to let your users know that your iPhone app is currently swapping data with the network, you can do so with this simple line of code:

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

Hide It

You guessed it: once you’re done showing it, to hide it again, just set the same UIApplication property to NO like so.

[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

How to Make the iPhone Vibrate

Dec 15, 2009   //   by Derek van Vliet   //   Development  //  1 Comment

The iPhone is capable of dazzling the user eyes by pushing impressive graphics around its screen and tickling their ears with a lot of audio to go with it, but you may want to give users of your iPhone app some additional sensory experience on top of that. You can do this by making the device vibrate.

We actually use the Audio framework to vibrate device. Here is how to do it in 3 simple steps:

1. Add the AudioToolbox framework to your target.

2. In the file you intend to trigger a vibration, import the AudioToolbox header file:

#import <AudioToolbox/AudioToolbox.h>

3. Finally, call the following line to make the device vibrate:

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

How to Retrieve Your App Delegate Singleton Instance

Dec 14, 2009   //   by Derek van Vliet   //   Development  //  3 Comments

You should be familiar with the application delegate class if you have ever developed any kind of iPhone app. It is the class that contains your app’s applicationDidFinishLaunching which most if not all apps use as an entry point for execution. You might use it to keep track of application-level state variables or objects, for example.

As such, from time to time you will have a need to retrieve your app’s application delegate instance. You can retrieve it from anywhere within your app by running the following single line of code:

MyAppDelegateClass *app = (MyAppDelegateClass *)[[UIApplication sharedApplication] delegate];

Just be sure to replace “MyAppDelegateClass” with your own iPhone app’s application delegate class name.

How to Get Your App’s Display Name and Version

Dec 13, 2009   //   by Derek van Vliet   //   Development  //  3 Comments

Have you ever needed to retrieve your iPhone app’s name or version at runtime? Sure, you can use constants in a lot of cases, but it can often save you time in the long run to make use of the information that is available via a class called NSBundle.

The Code

You can retrieve your iPhone app’s display name using the following one line of code:

NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"];

To retrieve your iPhone app’s version number, use the following similar line of code:

NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];

Use Case

Screen shot 2009-12-13 at 12.41.07 PMIn Addicus, when you click the “Get Set” button on the main menu, it links to our website and passes in the referring application name and app version as querystring parameters, allowing us to track visits to our website from different versions of all of our iPhone games. To do this, we combine the above code with code that opens a URL. Here is the resulting code:

NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"];
NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
NSString *url = [NSString stringWithFormat:@"http://getsetgames.com/?r=%@&v=%@",appName,appVersion];
 
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];

Since we’re retrieving this info via the NSBundle class, we never need to change this code when we update the version of the app. The version change propagates down to the URL we open automatically. And this code can be reused in any app without changing it.

How to Dial a Phone Number

Dec 12, 2009   //   by Derek van Vliet   //   Development  //  3 Comments

photo-4With so many awesome games and apps on the iPhone, it is easy to forget that it can actually be used to make phone calls. No, really, it’s true! And as is the case with so many other pieces of functionality, this is easy to accomplish with the iPhone SDK.

Like other phones, the iPhone supports the tel application protocol in URLs. This means that all we need to use is the trusty openURL method of the UIApplication class. We have previously discussed this method when pre-composing emails and, believe it or not, opening a URL.

The Code

Here is how to dial a phone number from your iPhone app in one line of code:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel:555-555-5555"]];

Dialing From a Web Page

You can also put links in your web pages that dial a phone number on the iPhone by using the tel protocol like so:

<a href="tel:555-555-5555">Dial 555-555-5555</a>

How to Hide (and Show) the Status Bar

Dec 11, 2009   //   by Derek van Vliet   //   Development  //  No Comments

On the iPhone’s 320×480 screen, pixel real estate is at a premium, especially for games. Often, the status bar represents 20 pixels of height that you as a developer just can’t afford to give away. Fortunately there are 2 simple ways to remove the status bar.

UIStatusBarHidden

uistatusbarhidden2The first way is by adding a setting to your app’s info.plist file called UIStatusBarHidden. This is ideal for apps that should never display the status bar. Just follow these steps to change the setting:

1. Open your iPhone app’s info.plist file.

2. Command-click and select Add Row.

3. Select “Status bar is initially hidden” from the drop down that appears.

4. Check the checkbox that appears next to the new row.

You could also add this setting to your app’s info.plist file by opening it in a text editor and adding the following 2 XML tags inside the <dict> tag:

<dict>
	<key>UIStatusBarHidden</key>
	<true/>
	...

How to Do it With Code

If you need the status bar to appear and disappear at runtime, then you will need to use code to do so. You can hide the status bar with one line of code:

[[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];

And to show it again, simply call the above line and pass “NO” into setStatusBarHidden instead of “YES”. You can also fade the status bar in and out by passing “YES” into the “animated” part of the message.

String Comparison Using NSString

Dec 10, 2009   //   by Derek van Vliet   //   Development  //  3 Comments

Photo-2a

One of the most common things a programmer needs to learn how to do when faced with a new API is how to compare one string to another to see if the two are the same or how they differ.

Because of this, many APIs have created some handy string comparison features, and the NSString class in objective-c is no exception. What follows are some invaluable tools for string comparison in objective-c.

The Is-Equal Method

The NSString class responds to a message and returns whether or not the NSString you pass in is equal or not:

NSString * str = @"oranges";
BOOL res = [str isEqualToString:@"apples"];

The Compare Method

The NSString class also has a method called compare, which gives you a bit more info in the return results. It can actually tell you the difference between the two strings; whether or not the string you passed in is:

  • the same,
  • in ascending sort order to the string you call the message on or
  • in descending sort order to the string you call the message on
NSString * str = @"oranges";
NSComparisonResult res = [str compare:@"apples"];
 
switch (res) {
	case NSOrderedAscending:
		// going up
		break;
	case NSOrderedSame:
		// even steven
		break;
	case NSOrderedDescending:
		// down i go
		break;
	default:
		break;
}

Insensitivity to Case

Finally, the NSString class also features a method for comparing strings without case sensitivity. This is useful for comparing strings with unpredictable case, such as user input. Like the compare method, it returns an NSComparisonResult enumerated value which allows you to see the equality or sort-order of the two strings.

NSString * str = @"APPLES";
NSComparisonResult res = [str caseInsensitiveCompare:@"apples"];
 
switch (res) {
	case NSOrderedAscending:
		// onward and upward
		break;
	case NSOrderedSame:
		// same old
		break;
	case NSOrderedDescending:
		// downfall
		break;
	default:
		break;
}

Our Games

Latest Tweets