Archive | Objective-C

Writing Apps for iPhone OS3, 3.2 and iOS4

The recent launches of iPad and iPhone4 have led to a flurry of activity on the iPhone operating system front. iPad launched with iPhone OS 3.2 but this OS was never destined for iPhone itself. iPhone 4 has introduced another OS release, with a nameshift from ‘iPhone OS’ to ‘iOS’ 4. iPhone and iPod users are expected to migrate to iOS 4, but the upgrade isn’t mandatory. Eventually no doubt the iPad will join iPhone on a universal OS, in the meantime, you’re likely to find that your having to support three, and maybe more, different versions of the OS, across various devices.

When you’re coding for a specific OS, you should not look at the version number and base your logic on that. Here is an example of what to avoid:-

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2)
        { /* do iPad stuff here */ }
    else
        { /* do iPhone stuff here */ }

Whilst that is a perfectly legitimate way to be looking up the OS version, in reality you are less interested in the OS version per se so much as the capabilities of the underlying OS. Code that might work today can easily break. Here for example, you iPad intended code is going to run on iPhone’s upgraded to iOS4.

Instead, you should use the class method available to NSObject and all descendants:-

+(BOOL) instancesRespondToSelector: (SEL) aSelector

So you could write, for example:-

if ([[UIApplication sharedApplication] respondsToSelector: @selector(setStatusBarHidden: withAnimation:)])
        { [[UIApplication sharedApplication] setStatusBarHidden: YES withAnimation: UIStatusBarAnimationFade]; }
    else
        { [[UIApplication sharedApplication] setStatusBarHidden: YES animated: YES]; }

Here we test whether we use the method setStatusBarHidden: or the newer method setStatusBarHidden: withAnimation:. This will compile and run under different OS versions and give us the required means to act according to OS capabilities.

This test can be particularly important when writing for newer version of the OS but looking to support older ones. Occasionally additional classes and methods that have previously been private are promoted to public use and are documented, but using these under older OS’s will still trigger the automatic rejection for using undocumented methods in the Cocoa Touch libraries. For example, UINib is a new class made available in iOS 4.0 for working with cached NIB files. Although this class was always there, it used to be out of bounds. Using this class in an app written for iPhone OS 3.x will lead to rejection. Testing methods for this class with ‘respondsToSelector’ will only return true if the method is public and you are entitled to work with it.

If you are looking to change screen layouts or other functionality depending on the actual device, Apple have created a new property of a UIDevice object. This macro will test whether you are on an iPad (UIUserInterfaceIdiomPad) or iPhone/iPod Touch (UIUserInterfaceIdiomPhone).

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
     {     /* The device is an iPad running iPhone 3.2 or later. */ }
else
      {  /* The device is an iPhone or iPod touch. */ }

Wrap this around views where you want to achieve different layouts according to the screen sizes, and anywhere else that you have iPad specific behaviour.

Posted in Development, iPhone, iPhone Development, Objective-C0 Comments

Delegation and Notifications, Oddities or Pure Elegance?

Objective-C and Cocoa Touch are strong on design patterns and principles. If you adhere to Apple’s way of coding then you’ll create reliable and reusable code. If you’re new to Objective-C, some of the design principles can be quite daunting and if your background is in other object oriented languages, some of the design patterns may initially appear quite alien.

Delegation and notifications present two such slightly odd patterns, but once you understand them they are actually rather elegant in what they achieve.

Delegation

Most people describe delegation as a method of subclassing, and essentially that’s right. Delegation wouldn’t exist though if it were simply an alternative to subclassing, so you can be sure that it solves other problems. I like to think of delegation almost as a work in progress – a class knows what it has to achieve and is implemented accordingly, but delegation allows a broad class to be written in such a way as to leave the final detail to future imagination. This is achieved by assigning your object as a delegate to a predisposed object; your new object can implement a bunch of methods that will be called by the delegating object whilst benefiting from the much broader underlying library.

The most common use of delegation must be handling UITableViews. The core Cocoa Touch library implements nearly everything a table requires in order to handle display itself, but how the cells are laid out, how your app responds to touches and so on is all left to your implementation. Most of the table handling code is given and you need not concern yourself to the inner workings, but you have to complete the final part – you must define how many sections there are in your table, how many cells in each section, how each cell will be laid out, whether there is a disclosure button and what should happen if the table is selected. All of this behaviour is defined by you – you are offered templated ‘hooks’ that you can fill in or remove depending on how you want your actual implementation to behave. Sometimes delegate methods are required to be completed, other times they are optional.

Cocoa Touch uses delegation extensively, indeed the main application is executed via delegation, hence your appDelegate. You’ll come across delegation in many other situations as you start creating apps for the iPhone and iPad.

Notifications

Another peculiar design pattern in Objective-C is that of notifications – that’s NSNotifications, not the more recently implemented Push Notifications. Notifications are very different to delegation and yet they share a common goal – both offer a way for remote classes to interact with your own objects.

An app has a ‘notification centre’ that is like a central switchboard within your app. Any method can send notices to the notification centre as it does its work. Any object can ‘tune in’ to the notification centre, choosing to listen to all broadcasts, or just to notices relating to particular topics. The API’s that you use with Cocoa Touch broadcast messages extensively in the background. You won’t be aware of this until you subscribe to notifications, and suddenly you’ll be inundated with reams of information as your app goes about its duties!

You can take advantages of notifications by responding to events that you wouldn’t otherwise have visibility of. For example, MPMoviePlayerController prior to iPhone OS 3.2 gave almost no access to know when a movie was stopped, started or when other buttons were pressed. Monitoring when a movie was stopped was widely documented – you subscribed to the relevant notification that the movie had stopped. But you could also subscribe to other notifications for other events triggered by the player controller and implement your application’s response accordingly.

In the same way that delegates can be used for a remote object to call a method on your own object, so notifications can be used as a way of triggering methods in your classes from a remote object. Whilst delegates can only have one object respond to them, notifications allow for many objects all to respond to a single event. Beware if you are working in a multithreaded environment because you can only subscribe to notices broadcast within your own thread.

Final Words

Delegation and notifications offer two design patterns used widely in Cocoa Touch, there are many more besides. All in all they each offer a distinct way of achieving some task; on the whole they add flexibility to the main workings of many of the Cocoa API’s, decoupling the bulk of the workings from the finer implementation. Often they allow the programmer to achieve some monumental tasks in just a few lines of code. How many lines of code to implement a table? …now consider how easily you could do it just using views and subviews and coding it from scratch!

Delegates and notifications are not the exclusive preserve of Apple – you too can create your own delegates and fire your own messages to the notification centre. Once you are familiar with Apple’s design patterns, perhaps you will adopt best practice and model them in your own classes?

Posted in iPhone Development, Objective-C0 Comments

Objective-C and the Properties of BOOL

At a basic level, boolean logic allows for a value to be either true or false, on or off, 1 or 0. The ways in which boolean types are implemented vary widely across languages and implementations. At the most granular level, computers work with bits that are either set to on or off, whereas some boolean data types in databases cater for three or even four values: 1, 0, null or undefined. Dennis Ritchie’s original C language lacked a boolean type at all but it was added in C99, and C’s primitive ‘bool’ type is available in Objective-C. ‘bool’ can be set to either true or false, 1 or 0.

Objective-C has implemented a more standard boolean property – it offers the BOOL type in addition to the primitive ‘bool’. The Cocoa and Cocoa Touch API’s use BOOL as the standard message response in favour of ‘bool’, so it is a property you must get to understand, and should code your own methods using BOOL as well.

Unlike most other things in Objective-C, BOOL is NOT an object, it is a raw data type. The standard values of BOOL are YES and NO rather than true or false, or 1 or 0. However, under the bonnet YES and NO are simply definitions given to the preprocessor as aliases for 1 and 0. In Cocoa Touch YES and NO are defined in NSObjCRuntime.h:-

#if !defined(YES)
    #define YES (BOOL)1
#endif

#if !defined(NO)
    #define NO (BOOL)0
#endif

This means that BOOL values are NEVER ‘YES’ and ‘NO’ so you cannot test them as such:-

if (myBOOL == 'YES') { ... }

…and they are NOT objects, so you cannot send the message:-

if ([myBOOL isEqualToString: @"YES"]) { ... }

Instead you must test them for true or false, or zero or non-zero:-

if (myBOOL) { ... }

or

if (!myBOOL) { ... }

If you want to log the value of a BOOL property using NSLog, then you can use the decimal signed integer format identifier %d:-

NSLog(@"MyBOOL value is %d", myBOOL);

Because BOOL represents 1 and 0 internally, you can also use the ternary operator to test BOOL values:-

myBOOL ? NSLog(@"Yes") : NSLog(@"No");

…and you can use this technique to convert between bool and BOOL should you so wish:-

mybool = myBOOL ? true : false;

Remembering that BOOL is NOT an object type makes it easy to remember how to declare BOOL properties, namely:-

BOOL myBOOL = YES;

…rather than using a pointer:-

BOOL *myBOOL = YES;

BOOL properties can be set with any of YES / NO, true / false or 1 / 0. All map back to 1 or 0.

Understanding that Objective-C’s BOOL data type is simply mapped to 1 and 0 makes working with BOOL values completely straightforward!

Posted in Development, iPhone Development, Objective-C2 Comments

KVO and Bindings on iPhone

‘Google’ for KVO and bindings for iPhone, and too many results tell you that KVO is not supported on the iPhone platform.  Well, if it wasn’t once, it is now, and it’s a really powerful feature.  KVO is Key-Value Observing – essentially you can add have one object ‘observe’ changes to a property of another object.  When that property changes, a callback is fired and you can trigger an action.  In many respects it’s similar to delegation or notifications, in this instance allowing a callback event to be triggered by changes in your objects.

KVO is commonly used to bind your application data to the interface so that whenever your data changes, the interface is automatically updated to reflect the change.  Here’s an example: imagine that you are writing a game and your score is stored in a property.  Rather than looping continually and updating the score on every iteration, you can observe your score and every time it changes, trigger the display to update automatically.

There are countless uses for KVO, and once you understand how it works, you will probably start using it regularly in your applications.  KVO also helps to implement a clean MVC architecture, although the callback MUST be implemented, so your view controller does require some prior knowledge of the architecture.

Implementation is really straightforward, but you do need to understand key-value coding.  Key-value coding (KVC) offers a different way to access properties of an object.  You’re probably familiar with:-

[anObject setProperty: @"Some string"];
 

or:-

anObject.property = @"Some string";
 

KVC allows you to access an object property by using a key, thus:-

[anObject setValue: @"Some string" forKey: @"property"];
 

If you are writing your own accessors you MUST comply with traditional naming conventions (setter = setPropertyName, getter = propertyName) because KVC assumes the names based on the key.  If you only need standard accessors, you can synthesize your properties and KVO works fine.

If you’re comfortable with that, then setting an observer is as simple as:-

[anObject addObserver:self forKeyPath:@"property" options: 0  context: NULL];
 

…then when ‘property’ in anObject is changed through the KVC method:

[anObject setValue: @"Some string" forKey: @"property"];
 

The observer fires an observer callback, passing in the key of the changed property.  By looking at the key value, you can trigger the appropriate work:-

- (void) observeValueForKeyPath: (NSString *) keyPath ofObject: (id)  object
change: (NSDictionary *) change context: (void *) context {
     if ([keyPath isEqualToString:@"property"] ) {
         // update your interface or do something else here...
     }
}
 

You MUST implement the observeValueForKeyPath: ofObject: change: context: method otherwise your app will crash.  Change allows you to access the old or new value, or both, and context allows you to pass in a pointer, enabling you to pass more information into your callback.

That’s pretty much all there is to KVO.  Observing can be quite resource intensive so try to avoid setting lots of observers.  If you want to track a lot of properties, look at implementing a single flag that can trigger work to update all of your properties.

Posted in iPhone Development, Objective-C1 Comment

Data Persistance on the iPhone

If you’re writing apps for the iPhone, sooner or later you will want to be able to persist data between sessions. You might want to store hi-scores, preferences, favorites, log metrics or achieve some other task. The iPhone supports three main interfaces for persisting data, ultimately they all write out to disk. In time you will probably find you use all three methods, each one suits different tasks.

Property Lists

Property lists, or plists, offer a way to write a dictionary of data (key – value pairs) out to a file. The native format is XML file, but you don’t need to load the file and parse it, you can simply read the file and de-serialize the information back into objects. To write out, you just create your dictionary object and serialize it to a file. Plists offer a lightweight method to store data and work well when you have a clearly defined set of objects to persist, perfect for hi-scores, favorites and preferences. Read the data in your application delegate in applicationDidFinishLaunching, and write it back out in applicationWillTerminate.

Reading and writing to Plists is pretty trivial. Once your ‘favorites’ data is stored in a dictionary:-

- (void)writeToFavorites: (NSDictionary *) myFavorites
{
    NSString *path = [[NSBundle mainBundle] bundlePath];
    NSString *filePath = [path stringByAppendingPathComponent:@"favorites.plist"];
    NSMutableDictionary* plistDict = [[NSMutableDictionary alloc]
                                      initWithContentsOfFile:filePath];
    [plistDict setValue:myFavorites forKey:@"Favorites"];
    [plistDict writeToFile:filePath atomically: YES];
}

…and to read it back in again:-

- (NSDictionary *) readFavorites
{
    NSString *path = [[NSBundle mainBundle] bundlePath];
    NSString *filePath = [path stringByAppendingPathComponent:@"favorites.plist"];
    NSMutableDictionary* plistDict = [[NSMutableDictionary alloc]
                                      initWithContentsOfFile:filePath];
    NSDictionary *myFavorites = [plistDict objectForKey:@"Favorites"];
    return myFavorites;
}

Plists support various data types including strings, numbers, arrays and dictionaries, so they can be used to store complex data structures and best of all, there’s no parsing to do!

SQLite

For more complex data interactions, nothing beats a good old fashioned database.  SQLite has been available on iPhone since its launch and historically was used in Apple’s core applications.  SQLite is available across platforms and is the workhorse for tasks inside many applications, for example Firefox uses  SQLite for tracking downloads, bookmarks, history and other tasks.

SQLite offers a lightweight SQL interface to your data.  Your application must create tables and write data into them using SQL commands.  As it’s name suggests, SQLite is ‘lite’ – although it offers RDBMS functionality, it has some quirky features when compared to traditional RDBMSs such as Oracle, Microsoft SQL Server, MySQL or PostgreSQL.  For example, most data formats boil down to a string representation, this leads to the dynamic typing capabilities of Perl or PHP!  Binary data can be stored in SQLite databases which means that whole objects can be stored out in much the same way that Plists can store data objects.

Working with SQLite on iPhone requires tools to support being able to view the state of your data as you develop your application.  Because of the app’s sandbox environment, you will need to store your database in the Documents folder inside your app directory.  There are a number of viewers for SQLite databases, I use the SQLite Manager plugin for Firefox which is perfectly adequate. When compiling for iPhone simulator you can drill down into the application directoryand view your database in situ,  To view a database on your iPhone, first you must pull the SQLite file onto your Mac using Xcode’s Organiser.  Download the database to your local disk and then open in the manager.  Be aware that each time you compile your app for Simulator, the app id changes, moving the database location with every run.

In order to use SQLite in your own projects, you must add the framework into your project in Xcode.  Right click on the Frameworks folder in your Xcode project and choose ‘Add existing framework…’.  SQLite is located at:-

/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOSx.x.sdk/usr/lib/libsqlite3.0.dylib

Make sure that you select ‘libsqlite3.0.dylib’ as this always points to the latest build of the version 3 framework.

The main SQLite website offers full documentation, learn more there about what SQL features are and are not supported.

Core Data:

This Cocoa framework was made available to iPhone OS 3 and is Apple’s preferred way to persist data.  Under the bonnet, Core Data actually uses either SQLite or Plists to store your data – it makes the choice.  Although this is Apple’s preferred method for persisting data, it may not be yours!

As with SQLite you must add the Core Data framework to your project – this is located with the other Cocoa frameworks.  Use Xcode’s Data Modeller to create your data structure, this is much like creating a SQL database with a GUI tool.  Once you’ve done that, Core Data methods give you a powerful interface to your data.

One good reason to favour SQLite over Core Data is that SQLite is more portable, and if you are looking to migrate your app between iPhone and Android, then you’ll be able to share code more easily.  Core Data does give you some pretty compelling features should you need them – undo capabilities in your app, spell checking and it automatically looks after persisting your data to disk.

- (void)readPlist
{
    NSString *filePath = @"/System/Library/CoreServices/SystemVersion.plist";
        NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];

        NSString *value;
        value = [plistDict objectForKey:@"ProductVersion"];

        /* You could now call the string "value" from somewhere to return the value of the string in the .plist specified, for the specified key. */
}

Posted in Development, iPhone Development, Objective-C0 Comments


Advert

For more information about our services…

Contact Us

Wordle of the Day

Image from software at http://wordle.net
Data by Web Trends Now

Categories