Tag Archive for iosdev

WWDC 2012 Keynote Let Down

Earlier today I hosted Coder Radio with Chris Fisher of Jupiter Broadcasting and in the episode we discussed my reactions as a developer to the WWDC keynote this year (2012). First things first. I did not attend WWDC nor have I installed the iOS 6.0 developer release, so some of my information may be incomplete; I have to do this in this way due to Apple’s developer NDA. You can listen to the show to hear what I didn’t like, but I’d rather go through a few things that I would like to have seen that to my knowledge aren’t coming.

Inter-app Communications
This is by far my largest pet peeve with iOS development and using iOS. Why isn’t there are robust way for apps to work together and share data; within reason of course. Android has a version this in the form of “intents” and Windows Phone 7 has a incredibly powerful system called “contracts”. This really gets to me when I consider that iOS is a BSD system yet does not adhere to the UNIX philosophy of allowing many small applications to work together to do big things; yes, I know that iOS apps tend to be smaller in scope than their desktop counterparts but to date there is no real way for them to work together. There is so much functionality that cannot easily be done on iOS due to this restriction.

Widgets
On my Android and Windows phone I can glance at the screen and get the latest tweets, view other data (such as a stock ticker), and play a song, or begin or pause listening to an audiobook. On iOS, almost all of those things require me to launch separate apps. That’s silly not to mention a bad user experience. I know there are definitely battery life concerns if you have too many widgets open, but there is no reason that Apple can’t add some sort of restricted mode for simple widgets to run in.

Siri integration
Ever since I got my hands on my 4S I have been waiting for a full Siri API. Apple has been working on it, but to date there is no fully functional Siri API for third party developers. This is understandable given how often Siri simply does not work but it is still a shame.

That’s all for now. Now I can finally take a look at the dev preview! For feedback please find me on Google+ or Twitter.

Programming Pitfalls: NSAutorelease Pools on iOS 4.X

iOS 5 has brought a lot of quality of life improvements in terms of memory management and the general iOS development workflow, assuming you are on the latest tooling. However, nothing is free and there seems to be a little bit of a pitfall that you might hit if you are testing predominantly on iOS 5.x: iOS 5 seems to deal with autorelease pools a bit differently than 4.

Here’s the situation:

- (void) viewDidLoad {
  [super viewDidLoad];
  [self performSelectorOnMainThread:@selector(yourMagicalMethod) withObject:nil     waitUntilDone:NO];
}

- (void) yourMagicalMethod {
  // do some magical stuff and set some objects to autorelease
}

This will run fine and without complaint on iOS 5. However, on iOS 4 it throws some errors in the log at runtime regarding no autorelease pool being set and leaks every object you set to autorelease in yourMagicalMethod. If that isn’t enough to crash your app, then your app will be in a highly unstable state and will be prone to crashing the next time you do something even somewhat intensive, such as call the camera.

I did some sleuthing with Instruments and found that yes on 4.x those objects are all leaked and yes they are not on 5. Luckily there is an easy solution that doesn’t involve any crazy version checks or (God forbid) compiler macros:

- (void) yourMagicalMethod {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

// do some magical stuff and set some objects to autorelease

  [pool release];
}

That’s it. All you need to do is create an autorelease pool in scope and release it. Both iOS 4 and 5 will be happy. I don’t know why this issues exists and I’d love to find out if you do. If you have questions or comments, I am on Twitter and Google+.

Simply Loading TableViewCells from a Nib

UITableViews drive a significant portion of iOS apps. Apple has provided some pretty great tools for developing decent looking apps based on them, but there are times when you might want to do something a little more stylish than what iOS provides. That’s when you probably consider writing your own UITableViewCell subclass or at least adding a category to UITableViewCell, though I find that is probably the less appropriate option in most cases. Getting your cells to look just right can be more than a little time consuming. Luckily, there is a bit of a shortcut you can take: loading the cells from a nib.

Before I show you how to do this, you should know going in that there are some drawbacks to doing this and that this is not an appropriate solution a some cases. Loading cells from a nib is less performant than just drawing the entire thing in code. Generally, you would not want to do something like this in a resource intensive app, such  as a game for example.  Ok, now that we have gotten that disclaimer out of the way, let’s get back to the point:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
   self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
   if (self) {
       NSArray* nibContents = [[NSBundle mainBundle] loadNibNamed:@"SpecialCell" owner:self options:NULL];
       NSEnumerator* nibEnumerator = [nibContents objectEnumerator];
       NSObject* nibObject = nil;
       while ((nibObject = [nibEnumerator nextObject]) != nil) {
           if ([nibObject isKindOfClass:[SpecialCell class]]) {
               self = (SpecialCell *)nibObject;
               break;
           }
       }
   }
   return self;
}

The above code presupposes that SpecialCell is a subclass of UITableViewCell; I omitted the header for the sake of brevity. So, let’s get the obvious stuff out of the way. This method is overwriting initWithStyle and yes you could write a second method rather than overwriting that one. We have the normal if (self) check that we see in inits. All pretty much standard.

Ok, so what is actually loading the nib? Well, if you look nib is being loaded and its contents are being placed in the nibContents array. Once the the contents of the nib are all in the array, an enumerator is created based on it. After that we simply loop through all of the objects, assign self the the one whose class is SpecialCell and return it.
Pretty easy, right? Just keep in mind that this can be a source of slow down on your table and may not be an appropriate solution for your app, but this can be a good time saver for prototypes or non resource intensive apps. If you have any feedback I can found Twitter or Google+.

Objective-C Singletons

A singleton is a way for developers to keep one and only one object of a class in existence for the entire lifecycle of an application; the nitpicky among you will note that there are portions of an app that might not have any instances of a singleton object, since it is common practice not create the singleton until you need it. Some example cases that you would use a singleton include: a player object for a game, a user object for a social app, and a shopping cart.

Creating a singleton is pretty simple:

@interface User : NSObject
static User* userSingleton;
+ (User *) userSingleton {
  if (!userSingleton) {
    userSingleton = [User alloc] init];
 }
return userSingleton;
}

Let’s walk through this. You declare a static user object called userSingleton, then whenver [User userSingleton] is called you check to see if that object is not null and either returns the existing object or alloc/inits the object, then returns it.

Ok, so that’s all well and good, but how do you actually use it. Well it’s simple. Let’s say our User class has a name property. We could access that with our singleton via:

[[User userSingleton] name];

Need to set the name?

[[User userSingleton] setName:@”Luke”];

Not bad, right? Also, note that all other messages can be sent via the same syntax, so:

[[User userSingleton] someMessage];

For those of you coming from a Java background sending a message in Objective-C would be called calling a method in Java.


Now you may have noticed that the above user object will have null values for all of its properties when it is first created and might want to be able to set some default values. For this example let’s assume that User has a few properties (name, fathersName, and saberColor):

static User* userSingleton;
+ (User *) userSingleton {
  if (!userSingleton) {
    userSingleton = [User alloc] init];
    [userSingleton setName:@”Luke”];
    [userSingleton setFathersName:@”Anakin”];
    [userSingleton setSaberColor:[UIColor blueColor]];
  }
return userSingleton;
}

As you can see, if the object is null, then we create it like before, but now we set some default values to its properties. Naturally, these values will be overwritten when you call their respective setters:

[[User userSingleton] setSaberColor:[UIColor greenColor]];


That’s pretty much all you need to know to get started with singletons in Objective-C. One thing of note about my code samples is that they assume you are using ARC, but you are not they still work; you will just have to include the proper retain/release calls. Hope this helps, please get in touch on Twitter or Google+.

***Update: An eagle-eyed reader pointed out to me that my sample here does not prevent you from creating a new instance of the object. So, if you created the object as I recommend but did User* badUser = [User alloc] init] you would have a new user object.  To get a true singleton (ie only one instance allowed) you would have to override alloc and a few other methods; The eagle-eyed reader recommends you see: http://cocoadev.com/index.pl?SingletonDesignPattern. Also, a few of you have gotten in touch with me asking why I did not show the GCD / block pattern. The reason for that is that I feel that it is too advanced for beginners but will write it up shortly. Thanks for all the feedback.