WWDC 2012 Keynote Predictions

It is that time of the year again were the Apple rumour mill runs wild in anticipation of the WWDC Keynote and this year is no exception. Unlike years gone by there isn’t a lot of information to go on, so I decided to make a list of the things that I would like to see announced, and the likelihood for each of them.

Mountain Lion

Release Date

We will get a release date (even if it is to the nearest month) for the next version of OS X. Mountain Lion has been in beta for a few months now and although there are a few bugs remaining, it feels like it is well on the way to release.

Likelihood 8/10

Dictation

The iPhone 4S introduced the world to Siri and the iPad 3 featured a stripped down version that just handled dictation. I think Mountain Lion will include the dictation aspect of Siri.

Likelihood 6/10

iOS 6

Background Triggers

I think Apple’s decision to not support true multitasking was correct to preserve battery life and performance of the active app, but there are more and more apps that need to check for data in the background e.g. Email, RSS, Offline Reading Apps. I expect there to be an API to register your app to be awoken to do such a thing at a given time interval e.g. Every hour, Every Day.

Likelihood 7/10

Inter-App Communication

Currently apps have to communicate with each other using the rather clunky URL schemes or even the pasteboard. There are plenty of things Apple could do to improve this, such as mimicking the full blown services approach found on OS X, or simply a “Files” App so it is easy to work on a file using multiple apps.

Likelihood 4/10

Facebook Integration

iOS 5 included Twitter Integration so users could easily Tweet from apps without having to authenticate their account every time. iOS 5 also included Twitter Request APIs making it easy to send data to and from Twitter. I see a similar OS Level of integration for Facebook in iOS 6.

Likelihood 9/10

Flickr, Vimeo etc Integration

In addition to Facebook I also expect there to be support for popular Photo/Video sharing services such as Flickr and Vimeo. I wouldn’t expect a rich API for these, just a simple interface to upload and download media from the built in apps.

Likelihood 7/10

Home Screen Widgets

I just don’t think Apple like widgets, so I don’t expect there to be any support for them in iOS 6 on either Springboard or in the Notification Center.

Likelihood 1/10

Apple Maps

It is obvious that Apple and Google are not the best of friends at the moment, and it is also clear that Apple doesn’t like to be reliant on anybody, so moving to their own Maps platform is a case of when and not if.

Likelihood 6/10

Siri Update

I expect Siri to get a few more features (maybe it will find businesses in the UK!!!), but I don’t expect it to be opened up to developers just yet.

Likelihood 8/10

Live Icons

If the Calendar app can update its icon to reflect the date why can’t the weather app update its icon to display the weather?

Likelihood 4/10

Apple TV SDK

The last 2 versions of the Apple TV run a variation of iOS (previously it was running a version of Mac OS X forked from 10.4), so it makes sense to unify it with the version of iOS that is on the iPhone and iPad. This will mean an API to handle events from the Apple Remote in addition to some new content APIs. Technically I don’t expect it to be too much of a challenge for developers, and it is an obvious area for Apple to move into.

Likelihood 6/10

Game Center Controller

If you haven’t seen Joypad (http://getjoypad.com/) before, it is a very cool idea. It turns your iPhone into a controller for iPad Games, but as Game Center is also coming to the Mac in Mountain Lion, an Apple supplied Game Center Controller App and API make a lot of sense to me.

Likelihood 5/10

iCloud

Unified Notifications

A large number of apps make use of Push Notifications for a variety of things, but they are not without their problems (and irritations). One of the major issues with Push Notifications is that people often have more than one Apple device, meaning that you get a Push Notification for the same event on all of your devices (which is expected), but annoyingly you have to dismiss notifications on all of the devices. I expect Push Notifications to be unified and synced using iCloud.

Likelihood 7/10

Reminders and Notes

I think that Reminders and Notes will now sync to the web based version of iCloud.

Likelihood 8/10

Safari Autofill Names & Passwords Sync

The transition from MobileMe to iCloud meant we lost the ability to sync keychain items between our Macs. In Mac OS 10.8 I expect this feature to be reinstated at least for Safari Names and Passwords, logically support for this will also be present in iOS 6.

Likelihood 8/10

webOS Synergy like Contacts and Calendars

One of the best things about webOS was how it merged all of your contacts and calendars together from all of the different services you had signed into (e.g. a person’s email address from iCloud, profile picture from Facebook etc). Now that we have iCloud, Exchange, Facebook and Twitter integration why can’t Apple implement a similar solution?

Likelihood 5/10

Hardware

iPhone 5

I don’t think we will see “The New iPhone” released at WWDC, simply because if the rumours are true and the only physical change is a bigger screen I don’t think that developers will need too much time to update their apps. Moreover Apple will have to make existing apps backwards compatible anyway (maybe by placing black bars around the edges?), so this reduces the requirement for it to be unveiled at WWDC.

Likelihood 2/10

MacBook Air/Pro

Even though both the MacBook Air and MacBook Pro received an update in the latter half of last year, I do expect a refresh and possibly a combining of the 2 lines leaving us with a 11", 13" and 15" MacBook Air. The rumor of a retina display would make this a very appealing update.

Likelihood 9/10

iMac

The iMac is also due an update, but due to the size of the screen I think the inclusion of a Retina display as standard is extremely unlikely.

Likelihood 7/10

Mac Pro

The Mac Pro hasn’t been updated for nearly 2 years, so many people think that it is dead. In my opinion it has become like the iPod Classic, whereby it is available to purchase if you need it (some people do), but it simply won’t ever receive a major update again. Saying this I would expect there to be one more minor update of the Mac Pro, but it will be an internals refresh rather than a complete overhaul.

Likelihood 8/10

Security Scoped File URL Bookmarks

Sandboxed applications (without any additional entitlements) live within their container (~/Library/Containers/apps.bundleidentifier_) and have no access to the rest of the File System, no access to the Internet, no access to Hardware such as the Camera, Microphone, USB Devices and Printing and has no access to User’s Data such as the Address Book, Location or Calendar.

Now this may seem a little extreme, but besides file system access all of these features can be enabled by requesting the relevant entitlement. For these features everything “just works”, but be warned you may be quizzed by the Apps Review Team why you require a given entitlement, so don’t just include them for the sake of it … or for analytics.

So now on to files…

When you sandbox your application you will have the following entitlements file (typically called appname.entitlements_):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.security.app-sandbox</key>
    <true/>
</dict>
</plist>

com.apple.security.app-sandbox simply enables app sandboxing for the given target:

com.apple.security.app-sandbox
Enables App Sandbox for a target in an Xcode project

As you can’t just access any file on the file system, the user has to select them (which means the powerbox will give you temporary access to the URL of the file). To do this the user can use drag and drop, or use NSOpenPanel/NSSavePanel. For this example we will use NSOpenPanel for clarity. To use NSOpenPanel/NSSavePanel you need to include the following entitlement:

com.apple.security.files.user-selected.read-write
Read/write access to files the user has selected using an Open or Save dialog

NSOpenPanel is trivial to implement and you get access to a file URL in the completion handler:

NSOpenPanel *openPanel = [NSOpenPanel openPanel];

[openPanel beginSheetModalForWindow:[self window] 
completionHandler:^(NSInteger result){

if (result == NSOKButton) 
{
    NSURL *openPanelFileURL = [openPanel URL];
}

}];

By using NSOpenPanel you now have access to the given file URL (and therefore file) until your application quits. Under certain circumstances you also get access to the file URL when you application launches if the application supports resume.

So what if you need to access files across launches?

You need another entitlement of course, in this case you have 2 choices depending on if your Application is a Document Based Application:

com.apple.security.files.bookmarks.collection-scope
Ability to use document-scoped bookmarks and URLs

or a Non-Document Based Application:

com.apple.security.files.bookmarks.app-scope
Ability to use app-scoped bookmarks and URLs

Assuming your application is a Non-Document Based Application your entitlements file will now look like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.security.app-sandbox</key>
    <true/>
    <key>com.apple.security.files.user-selected.read-write</key>
    <true/>
    <key>com.apple.security.files.bookmarks.app-scope</key>
    <true/>
</dict>
</plist>

First of all you need to get access to the file URL in the same way as you did before, but this time you are going to create a bookmark out of it using NSURLBookmarkCreationWithSecurityScope:

NSURLBookmarkResolutionWithSecurityScope
Specifies that the security scope, applied to the bookmark when it was created, should be used during resolution of the bookmark data.
NSError *error = nil;
NSData *bookmarkData = nil;

bookmarkData = [openPanelFileURL 
bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope
includingResourceValuesForKeys:nil
relativeToURL:nil
error:&error];

You can now store this bookmark (which is just a NSData object) in any way you choose, as long as you can retrieve it later.

When you want to access this file you need to convert the bookmarkData into a file URL:

NSError *error = nil;
BOOL bookmarkDataIsStale;
NSURL *bookmarkFileURL = nil;

bookmarkFileURL = [NSURL 
URLByResolvingBookmarkData:bookmarkData
options:NSURLBookmarkResolutionWithSecurityScope
relativeToURL:nil
bookmarkDataIsStale:&bookmarkDataIsStale
error:&error];

The URL returned includes a “security scope” appended to it (although this cannot be assumed):

file://localhost/Users/ObjColumnist/Desktop/File?applesecurityscope=373861333331353430643963323736623939346438646161643134663339363061396361306534303b30303030303030303b303030303030303030303030303032303b636f6d2e6170706c652e6170702d73616e64626f782e726561642d77726974653b30303030303030313b30653030303030323b303030303030303030306535363566373b2f75736572732f7370656e6365722f6465736b746f702f77617463686564

You then need to tell the OS that you are going access this file URL:

[bookmarkFileURL startAccessingSecurityScopedResource];

This allows you to do anything you want with that file URL, typically you will use NSFileManager to do this.

Once you are done accessing this file URL you MUST tell the OS, failing to do so will leak kernel resources and prevent you from accessing secured files until you quit your application.

[bookmarkFileURL stopAccessingSecurityScopedResource];

This wraps up Security Scoped File URL Bookmarks on OS X and how you can access files outside of you application’s sandbox container. It is important to note that you don’t have to do this for files that reside in your application’s container, and this article doesn’t do any error handling when converting URLs to Bookmarks and Vice Versa.

Is the Latest Always the Greatest?

After watching the various feeds regarding Apple’s media event this Wednesday, I picked up my iPad (1st generation) and went to download the new iPhoto app. Unfortunatley I was out of luck, as it said I needed a camera (why? If I had a Mac without a iSight Camera would Apple prevent me from using iPhoto on my Mac?). Thankfully I have an iPhone 4S, so I went to the App Store and was presented with the following Updates screen:

App Store

Now at first glance you may just think Apple have been busy, but if you look closely they updated some of their existing applications to requires iOS 5.1, a version of the OS which had only been available for a few minutes (and a version of the OS that refused to download due to server load!!!).

This made me think, If Apple requires users to update their devices to latest version of the OS to use their Apps, why don’t all developers?

The common approach of developers is to change the minimum specification of their applications only when they release a major version, but why does it have to be this way?

If we only supported the latest version of OS (and I mean even a point release) we would have the benefits of:

Now using the latest APIs actually has a number of benefits: So whats the downside? The only downside is quite a big one and that is:

But who are these users that don’t run the latest version of an OS? All iOS devices that have been avaliable for purchase in the last 2 years (not many people keep their phones beyond this) can upgrade to the latest OS for free. Since Over the Air Updates where introduced in iOS 5, the process of upgrading the OS on your device has become quick and painless. So my argument is, if all applications required the latest OS version to work, then maybe users would be more eager to upgrade their OS anyway…

We have something you really have to see. And touch - Media Event Predictions

So it is time for Apple’s first Keynote of the year (or do we count the educational event in January? … it did show up in the Keynote Podcast Feed after all), and the one prediction that everyone seems to be agreeing upon is that we will see the unveiling of the iPad 3, but what will be new…

iPad 3

Retina Display

The iPad 3 will have a 2048x1536 Retina Display (4 times as many pixels as the iPad 2’s display), meaning that text will be sharp and crisp and your be able to watch 1080p videos with (quite a lot of) pixels to spare. To put this into perspective, the 27" iMac has a resolution of 2560x1440, which means the iPad will actually have more lines on the screen than the 27" iMac. There is an unfortunate side effect of the iPad getting a Retina Display, and that is applications will probably increase in size with all of the iPad @2x images.

A6 Quad Core Processor

One thing that we know for sure is that the iPad 3 will need quite a bit of a speed bump to push all those pixels around the screen, but will it be a newer Dual Core A5 or a Quad Core A6 Processor? One of the rumors is that the iPad 3 will be slightly thicker than its predecessor, and I think this is to accommodate a bigger battery for a Quad Core Processor.

Improved Camera

The iPhone 4S’s camera is the one of best cameras that you will find on a smartphone, the iPad 2’s camera on the other hand is probably not as good as the original iPhone’s. The Retina Display would emphasise how bad the cameras are on the iPad, so I expect Apple to bump the spec of both of the cameras so that they can at least both record video at 1080p.

LTE

It is early days for LTE, but I don’t think that there is any doubt that it will be the standard for the next few years, and unlike CDMA this will include outside of the US too. Maybe LTE is why the iPad 3 will put on a few pounds?

What else?

AppleTV 3

Continuing on the theme of 1080p, I think that we will finally get an AppleTV that is able to play 1080p videos which will also mean…

1080p iTunes Videos

I think Apple will start selling 1080p videos, which means that they are (theoretically) the same quality as Bluray. This means that videophiles will have nothing left to complain about… unless they still have a dial up internet connection as those video files will be huge.

What we won’t see

Thunderbolt Syncing

Am I the only person who still syncs their iPad using a USB cable? Hopefully I am not, but it would be good if you could sync your iPad in seconds over Thunderbolt. Unfortunately I don’t even think Apple will be adding to the tiny (mini? … nano?) list of device that currently uses Thunderbolt.

128 GB of Storage

With 1080p Videos and Retina apps everyone would like a bit more storage wouldn’t they?

iOS 6

I don’t think we are too far away from the developer preview of iOS 6, but I think that Apple will have an event just for iOS 6 (especially if it is a major release).

Shipping a 1.0 is Hard

The first version of an application is different to any other, and it is the hardest one to actually ship. This is especially true if you are an indie developer.

When you start a new application you probably have a list of features and a sketch of what you think/hope/wish the 1.0 version of your application will look like. As an indie developer you are the only one that knows exactly what is on this list, but you often feel like you can’t release an application until the whole list is completed, even though nobody else would be any the wiser.

The other major difference about a 1.0 version of an application is the lack of immediate pressure to release it. When you have released an application you are often pressured into releasing an update for a new feature or simply to fix some bugs. As an indie developer the only pressure you get is from yourself (and I try not to moan at me too often).

So over a week ago I finally decided my baby was ready to see the world, so I sent off the 1.0 version of my application Actionify to Apple and waited for it to go through the review process. To my pleasant surprise there was no problems first time round (Apple usually find something) and Actionify was released on Friday. Actionify is a GTD inspired Task Manager, that also offers a cloud sync subscription that allows users to collaborate on Projects. If you want to know more about it, you can click on the link here, but I won’t overload this post info. I am very pleased with how Actionify has turned out, the 1.0 misses a few features from my original list but also some additions that I added due to the feedback I received during the beta testing (thank you testers!!!). Inevitable it took longer than I had originally hoped, but this was mainly down to me underestimating the amount of effort and paperwork it took to set up a limited company (in the UK) and everything that goes with that (e.g. Banking, Transferring my iTunes Connect Account etc etc). In terms of development time the project probably only over run by 1 or 2 months, while this is not ideal, it isn’t to bad either.

In terms of technology, Actionify requires Mac OS 10.7 as the UI is mainly built with view based table views and the new Core Data APIs. I think view based table views shaved about 2 months off of my development time, so support for 10.6 wasn’t really an option for me. 10.7 also has a JSON Parser (NSJSONSerialization) and Popovers (NSPopover) built in, and although there are open source projects that offer similar functionally, I prefer to only depend on code by Apple and myself (rightly or wrongly) wherever possible.

The application syncs with a Rails application that I host on Heroku, and I couldn’t recommend Rails and Heroku enough. Rails is a great framework and Ruby is a great programming language, the best thing about Rails (for a non web developer) is everything has its place. Rails forces you to have a certain folder structure and I found this extremely beneficial … you can also add features with only a few lines of code which can only be a good thing. Heroku’s main benefit is you don’t have to think about servers and you just have to worry about your app. You simply deploy your code using a git push and you’re done. Moreover the majority of basic Heroku Add Ons are free, so you can start using Heroku without any risk (I am honestly not on commission, I just like it :) ).

I want to end this post by saying no matter how many times you release an application, seeing other people downloading it and using it is always the best feeling a developer can get, so if you can … SHIP IT!!!

Keeping the Static Analyzer Happy: Prefixed Initializers

The latest version of Xcode ships with LLVM 3.0 as it’s default compiler, and one of the first things that you will notice is that is a lot more thorough when it analyses your code compared to previous versions (which can only be a good thing). One thing that the static analyser now warns you about, is that you are over releasing objects that are returned from prefixed intalizer methods (init), such as in a category (for my previous posts on categories see here and here).

For example my NSString category has the following method:

- (id)MCSM_initWithComponents:(NSArray *)components 
seperatedByString:(NSString *)seperator;

And it’s implementation looks like this:


- (id)MCSM_initWithComponents:(NSArray *)components seperatedByString:(NSString *)seperator {

    NSMutableString *componentizedString = [NSMutableString string];

    NSUInteger i = 0;
    for(NSString *component in components) {

            if (i == 0) {
                    [componentizedString appendString:component];
            } else {
                    [componentizedString appendFormat:@"%@%@",seperator,component];
            }

            i++;
    }
    return [self initWithString:componentizedString];
}

This method takes an array of strings, and joins together using the separator parameter and can be used in the following way:

NSArray *components = [NSArray arrayWithObjects:@"one", @"two", nil]; 
NSString *string = [[NSString alloc] MCSM_initWithComponents:components seperatedByString:@","];
NSLog(@"%@",string);
[string release];

This would output:

one,two

As this method is in a category of NSString I don’t want it to clash with any other implementations. The common practise in Objective-C is to prefix categories methods (due to the lack of namespaces), so I have with MCSM_. The issue is that the static analyser will now think that this method returns an autoreleased object, as the method does not begin with init, new, copy or alloc. This means when you release the object the static analyser will complain about you over releasing an object.

So how do you fix this?

To fix this you can tell the compiler that the method returns a retained object by using the source annotation NSRETURNSRETAINED, which means your interface would look like the following:

- (id)MCSM_initWithComponents:(NSArray *)components 
seperatedByString:(NSString *)seperator NS_RETURNS_RETAINED;

Instead of NSRETURNSRETAINED you can also use __attribute((nsreturnsretained)), which is a longer way of writing the same thing:

- (id)MCSM_initWithComponents:(NSArray *)components 
seperatedByString:(NSString *)seperator __attribute__((ns_returns_retained));

So thats all fixed? Unfortunately not quite yet. The static analyser will now complain about a memory leak, as we have allocated a NSString by doing [NSString alloc], but then it isn’t referenced again in our code. For a method that begins with init, the static analyser knows that the method consumes the variable (which means it releases the parameter upon completion), and that is the behaviour we need.

To do this we have to use the source annotation __attribute((nsconsumesself)) in conjunction __attribute((nsreturnsretained)), which means your interface will look like:

- (id)MCSM_initWithComponents:(NSArray *)components 
seperatedByString:(NSString *)seperator __attribute__((ns_consumes_self))__attribute__((ns_returns_retained));

And that will fix it.

Summary

You don’t need to use the source annotations if your code obeys the Objective-C naming conventions, but in certain circumstances like the one above you need to help the Static Analyser do its job. As LLVM forms the the backbone of Automatic Reference Counting (ARC), you still need to do this even if your not retaining and releasing memory yourself.

Steve Jobs 1955-2011

Having never met the man, it does feel strange that I am so deeply sadden by Steve Jobs passing, and I suppose that is because what I do today is really down to him. Not only did Steve Jobs have the vision to create the Mac, iPhone and iPad that are in front of me on my desk, he also had the passion to make me want them too.

Looked up to by millions, Steve Jobs was a charismatic visionary, who will go down as one of the greatest, if not the greatest CEO of all time. Not only did he start the computing revolution when he founded Apple in 70s, in his second stint as Apple CEO he brought a company on the brink of bankruptcy to be the most valuable company in the world in just under 15 years. Time and time again he ripped up the rule book and released product after product that change the world for good.

I could go on about how he changed the world but you already know that, and there are plenty of other articles that put it better than me. What I would like to say is that Steve Jobs’ passing has reiterated 3 things to me:

Find what you love

You’ve got to find what you love. And that is as true for your work as it is for your lovers.
Steve Jobs, Standford Speech (2005)

Don’t settle for second best, this is as true as it is for work as it is for love. You need to find what you love doing, and do that. If it makes you millions then thats great, but if it makes you happy then thats what counts.

Work hard to make it simple

That’s been one of my mantras - focus and simplicity. Simple can be harder than complex: you have to work hard to get your thinking clean to make it simple. But it’s worth it in the end because once you get there, you can move mountains.
Steve Jobs, Interview with Business Week, 1998

If you design an make stuff like me, your appreciate that one of the things that Steve Jobs has proven, is that users are willing to pay more for simplicity.

My favourite Steve Jobs Quote is:

Design is not just what it looks like and feels like. Design is how it works.

This goes hand in hand with simplify, it has to appear simple to use and be simple to use. Attention to detail in every aspect of design is key to a successful product. Make this your Mantra.

All good thing must come to an end

No one wants to die. Even people who want to go to heaven don’t want to die to get there. And yet death is the destination we all share. No one has ever escaped it.
Steve Jobs, Standford Speech (2005)

No matter how visionary you are, no matter how much money you have in the bank, one day you will be gone. Not everyone like Steve Jobs has the chance to become a legend, but you do have the chance to leave a legacy.

Stay Hungry. Stay Foolish.

Let's Talk iPhone Keynote Predictions

So tomorrow is the day that we finally get to see the successor to the phenomenally successful iPhone 4, but what is going to be new?

iOS 5

The one thing that the new iPhone is guaranteed to will ship with iOS 5. If you have not already seen the WWDC Keynote (if not why not?) then you already know whats coming in iOS 5. As a reminder you can look on Apple’s Website. The biggest change is how notifications work, they are less obtrusive and are all visible in one place. The other change that you will notice straight away (if you also have friends running iOS 5) is iMessage. iMessage is Apple’s awnser to RIM’s Blackberry messagener. It allows you to send free message to other user’s iOS devices, and you also get the option of recieving sent, received and read receipts.

iCloud

Although strictly speaking part of iOS 5, iCloud is a headline feature all of it’s own. It allows applications to store data “in the cloud” so it is accessible on all of your devices, be it iPhone, iPod Touch, iPad, Mac or one of those PC things. An important thing to note which differentiates iCloud from services like DropBox, is that applications can only see their own data (it is sandboxed by company). So for example, you can’t edit a photo in one application, and then upload it using another application by finding the edited image on the file system, in fact as a user you can’t even see your iCloud file system at all!!

A5 Chip

The iPhone 4 has an under clocked version of the iPad’s A4 processor, so it would make sense that new iPhone will have an under clocked version of the iPad 2’s A5 processor. The A5 processor (on the iPad 2 at least) has two cores, which will make your iPhone experience a little bit more snappy.

8MP Camera

Not confirmed by anyone, but it would make sense (and would also be relatively cheap) to put a higher quality camera in the new iPhone. Bumping up the megapixel count for 5MP to 8MP is a logical step, and a few phones already contain this sensor.

64 GB of Storage

The iPhone has been stuck at 32GB of storage since the arrival of the 3GS, so I expect an upgrade to 64GB so I am able to carry half of music collection, instead of a quarter of it. (I could really do with a 128GB iPhone if you couldn’t tell)

iPhone 5 or 4S

If I was Apple, I would call it the iPhone 5 how ever minor the update is, and that is for 2 reasons:

  1. I think people are more likely to upgrade to an iPhone 5, as subconsciously it just sounds like a bigger update
  2. If it is called the iPhone 4S, then what is the next iPhone going to called? The 6th iPhone surely can’t be called the iPhone 5. (I know there has been a 3GS, but that was because Apple called the 2nd iPhone, the iPhone 3G)

Other Updates

In addition to the iPhone, I expect the iPod Touch to get an update so it’s specifications are inline with the new iPhone’s. I don’t think it will get a 8MP camera though, but we might even see a 128GB Model. If we do see a 128GB Model, I do expect the iPod Classic to retire to the gadget museum. If we don’t see a 128GB, I don’t expect to see an iPod Classic update anyway … does anybody still buy them?

The iPod Nano will also get a refresh for the holiday season, now wouldn’t it be amazing if that run iOS 5…

Adding Block Support to Existing Classes (Without Subclassing)

Blocks are great aren’t they? Amongst many other things, they allow you to put all your completion logic right next to where you call an asynchronous method. Apple has added block support for completion handlers in such APIs such as Core Animation, in fact I have already done a post on this previously. But what do you do, if the class you want to use is stuck in the past and still uses the older delegate style approach. This is where you have to write a method to handle all the delegate callbacks for a given class? Well thankfully there is a nice and clean way of adding block support to a class using a category.

I’ve previously written 2 posts on categories (which you can find here and here), and how they allow you to extend a class’s functionality by adding additional methods to it without subclassing it. The key word being methods (or indeed selectors if your getting technical), and not properties or instance variables. If you need to call a block after an asynchronous action has completed, you’re going to have to store it somewhere in the meantime, and that is the main focus of this post.

Take UIAlertView for example, you need to register for a callback when the user presses a button.

So you’d often have something like:

- (IBAction)showAlert:(id)sender {    
    UIAlertView *alertView = nil;

    alertView = [[UIAlertView alloc] initWithTitle:@"YES or NO"
    message:@"Select One" 
    delegate:self 
    cancelButtonTitle:@"NO" 
    otherButtonTitles:@"YES", nil];

    [alertView show];
    [alertView autorelease];
}

Then you would need to implement a method with the correct signature to handle it:

- (void)alertView:(UIAlertView *)alertView  didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if(buttonIndex == 1) {
        // Do Something
    }
}

This may look fine in the above example, but in a real iOS application the callback method may have to handle lots of different alert views, and we still have the handler code separated from where we actually setup and show the alert view.

So how can we solve this?

We are going to add a completion handler to UIAlertView, which doesn’t return anything and takes the button index we get given by the UIAlertViews delegate method as a parameter. To keep things clean we will define our completion handler in our categories header: objc typedef void(^MCSMUIAlertViewCompletionHandler)(NSUInteger buttonIndex); So the first thing you will need to do is set the completion hander block on an alert view and store it for when we get the delegate callback. For this we will use the Objective-C runtime function: objc_setAssociatedObject.

The objc_setAssociatedObject function takes 4 parameters:

  1. The object that you want to add the association too, in this case the UIAlertView
  2. The unique key so you can retrieve the value later
  3. The value you want to associate, which in this case is the completion handler block
  4. The association policy, which tells the runtime wether this association retains, copies or assigns the value.

The best way to describe how this function works, is that it treats an object like and NSDictionary. It allows you to set a given value for a given key, but unlike NSDictionary you can specify if the value is assign, retained or copied.

To use this method you need to include the runtime header:

#import <objc/runtime.h>

And we will define our key as a constant to keep things tidy, and so we don’t make any typos later on:

NSString * const MCSMUIAlertViewCompletionHandlerKey = @"MCSMUIAlertViewCompletionHandlerKey";

Then in another category method on UIAlertView all you need to do is set the alert view as its own delegate, and store the block as an associated object:

- (void)MCSM_setCompletionHandler:(MCSMUIAlertViewCompletionHandler)handler{
self.delegate = (id<UIAlertViewDelegate>)self; 

objc_setAssociatedObject(
self, 
MCSMUIAlertViewCompletionHandlerKey,
handler,
OBJC_ASSOCIATION_COPY_NONATOMIC);

}

As the UIAlertView is now it own delegate, it will receive the alertView:didDismissWithButtonIndex: callback. In this method you will need to retrieve the completion handler block so you can call it with the button index argument. To do this you will need to use another Objective-C runtime function objc_getAssociatedObject

The objc_getAssociatedObject function takes 2 parameters:

  1. The object to retrieve the association from
  2. The unique key for the association

This will mean that you end up with a method looking like this:

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {    
    // Get the Handler
    MCSMUIAlertViewCompletionHandler handler = (MCSMUIAlertViewCompletionHandler)objc_getAssociatedObject(
    self,
    MCSMUIAlertViewCompletionHandlerKey);

    // If there is a handler call the handler
    if (handler) {
        handler(buttonIndex);
    }

    //Release the block by setting the associated object to nil
    objc_setAssociatedObject(
    self, 
    MCSMUIAlertViewCompletionHandlerKey, 
    nil, 
    OBJC_ASSOCIATION_COPY_NONATOMIC);
}

So now that we have added this category to UIAlertView, all we have to do is update the code that creates and shows the alert view:

- (IBAction)showAlert:(id)sender {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"YES or NO"
    message:@"Select One" 
    delegate:self 
    cancelButtonTitle:@"NO" 
    otherButtonTitles:@"YES", nil];

    [alertView MCSM_setCompletionHandler:^(NSUInteger buttonIndex) {
        if (buttonIndex == 1) {
            // Do Something
        } 
    }];
    [alertView show];
    [alertView autorelease];
}

You can grab the code for this on Git Hub here and have a play with it yourself.

Mac OS 10.7 Lion - My Favorite new APIs

So after months of waiting, Mac 10.7 has finally been released to the general public. Although it has been given some minor spit and polish on the UI front when compared to it’s predecessor Mac OS 10.6, most of the improvements are under the hood. Thankfully the majority of these changes have been made available to developers in the form of APIs. With that in mind I thought I would point out some of my favourite new APIs that I have been using in the developer previews.

NSPopover

NSPopover works a lot like UIPopoverController on iOS. You give an NSPopover an instance of NSViewController (or one of your subclasses), and you can then present this view controller in a popover.

- (IBAction)showPopoverFromButton:(id)sender {
// Create the popover
popover = [[NSPopover alloc] init];

//Set the content view controller
popover.contentViewController = popoverViewController;

popover.animates = YES;

//So we get told when the popover has closed
popover.delegate = (id<NSPopoverDelegate>)self;

[popover showRelativeToRect:[sender bounds] ofView:sender preferredEdge:NSMaxYEdge];
}

The APIs for NSPopover are nice and simple, but in true Mac OS fashion the delegate callbacks take the form of NSNotifications rather than selectors.

- (void)popoverDidClose:(NSNotification *)notification {
    if ([notification.object isEqualTo:popover]) {
         [popover release]; popover = nil; 
    }
}

If you need to implement something like NSPopover in previous versions of Mac OS, then I recommend taking a look at MAAttatchedWindow.

CoreData

CoreData has had so many updates in Mac OS Lion it is hard to know where to start. Most of the API changes are to incorporate features that are needed to support Versions and iCloud Syncing. What this means is when you modify files Versions and iCloud only want to know the changes that have been made to a file, so they only need to store or transfer the differences between the original and the new file. This approach not only saves space (only the changes are stored, not another whole file), and it also means the versions of the file can easily be compared and contrasted (I am guessing that Apple uses GIT for this). If your application persists any data (and who’s doesn’t?), then you must look at CoreData as it gives you so many things for free.

NSOrderedSet

An ordered set, isn’t that just an array? Well in reality it is, it is an array that makes sure that the objects that it holds are unique and therefore not duplicated. That in itself isn’t that exciting, but what is exciting is that it allows you to have ordered Core Data relationships by simply ticking a box. These ordered relationships do incur a performance penalty over non ordered relationship, so don’t use them for the sake of it.

Concurrency

One of the major issues with CoreData is that NSManagedObjectContexts and therefore the NSManagedObjects that it contains, are not thread safe. In Lion NSManagedObjectContext has the initialiser method initWithConcurrencyType, which allows you to tell an NSManagedObjectContext to mange all of it’s interactions using its own private dispatch queue. This means by using Grand Central Dispatch you can reduce the complexity of concurrency when using CoreData in Mac OS 10.7.

Full Screen Windows

The full screen APIs are incredibly simple to implement (as long as your window resizes to the size of a user’s screen).

All you need to do is set the window’s collection behaviour to support full screen:

[window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];

This one line of code gives you the “full screen button” in the top right hand corner of the window.

If you want to make the window go full screen yourself, you just need to call the toggleFullScreen method on NSWindow:

[window toggleFullScreen:nil];

View based Table Views

My favourite new class is without a doubt NSTableCellView, as it allows you to use a (subclass of) NSView as a table view cell, rather than an NSCell (which is my least favourite class if you are asking). This makes things a lot easier to build custom UIs in a table cell, and also means it can have subviews such as NSButtons that can receive mouse events.

The two data source methods you must implement are:

- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView;

- (NSView *)tableView:(NSTableView *)aTableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row;

Although this makes NSTableView a lot more like UITableView it is important to note that NSTableView doesn’t support sections (as you may have guessed by the numberOfRowsInTableView method not being called numberOfSectionsInTableView). To make things slightly more confusing, NSTableView does however support group rows. Group rows float above the non group rows below it, which means they behave like iOS section headers.

You can tell the table view that a cell is a group row by using the delegate method:

- (BOOL)tableView:(NSTableView *)tableView isGroupRow:(NSInteger)row;

If you are creating a custom NSTableCellView in code, don’t forget you can override isFlipped to flip the coordinate system and make it like the iOS co-ordinate system.

Also don’t forget that as NSOutlineView is a subclass NSTableView, so it also supports view based cells.

In App Purchase

In App Purchase for iOS has been in the press for all the wrong reasons recently, but it is a great API for Mac OS X developers to have, so they can unlock different features in their applications. The API is very similar to it’s iOS counterpart besides when it comes to receipt validation. For more information on this I recommend watching the WWDC session 510, which is all about In App Purchase.

Push Notifications

Another feature ported across from iOS, but this time with less features. On Mac OS push notifications can only contain a badge value and not an alert and/or sound.

So thats a wrap up of my favourite new APIs in Lion, the standout ones for me being View Based Table Views and NSPopover. There have been so many updates I recommend looking through the change list, as you never know what you might find.

Page 3 of 6