1. Bullet Proofing your App

    Thanks to the Deployment Settings, we can deliver an application that supports earlier versions of the OS. But for every major OS release, a new bunch of APIs are included by Apple. Should we refrain our desire to include these cool new features? Never, thanks to the dynamic nature of Objective-C we can safely code our way out of trouble and have fun with new features.

    Classes

    Let’s say you want to include MKUserLocation new in iOS 3.0 but still be able to run your app in 2.0? Then use NSClassFromString which takes an NSString as parameter and will return nil if it can’t produce the class, or the class itself.

    Class userLocationClass = NSClassFromString(@"MKUserLocation"); 
    
    if ( userLocationClass != nil ) {
        MKUserLocation *userLocation = [[userLocationClass alloc] init];
        // Use userLocation
        [userLocation release]; 
    }
    

    Methods

    Methods are also added to classes. For instance, NSDictionary is a venerable class, and enumerateKeysAndObjectsUsingBlock: is one of the many methods that benefit from blocks included in iOS 4.0. To prevent any issue, we just bracket the call to this API inside a call to respondsToSelector:, an NSObject method that will return YES if the object queried will be able to perform the method.

    NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"some object", @"key", nil];
    
    if ( [dict respondsToSelector:@selector(enumerateKeysAndObjectsUsingBlock:)] ) {
        [dict enumerateKeysAndObjectsUsingBlock:^(id, id, BOOL *) {
            // dealing with the enumeration of the dict. 
        }]; 
        [dict release]; 
    }
    

    Functions and Constants

    For functions and Constants, we just need to see if there mapped into memory, for instance the ABPersonCopyImageDataWithFormat() function from AddressBook Framework included in the last iOS version, or the kCVPixelBufferPoolMinimumBufferCountKey constant from Quartz.

    if ( &ABPersonCopyImageDataWithFormat != nil ) {
        ABPersonCopyImageDataWithFormat(person, format); 
    }
    

    http://gist.github.com/615632

    http://gist.github.com/615627

    http://gist.github.com/615630

    http://gist.github.com/615631

Notes

  1. volonbolon posted this