Easily testing if a string is nil or empty

February 27, 2013 in iOS Snippets

A very common idiom:

if ([string length]) {

// It's a string of at least one char, and is not null.


Works because calling a method on nil is not an error – just silently returns nil, which is also false.

Proper thread-safe singleton

February 26, 2013 in iOS Snippets

The following is a correct thread-safe implementation of the singleton +sharedInstance method, which relies on GCD:

+ (id)sharedInstance;
 static id sharedInstance = nil;
 static dispatch_once_t once = 0;
 ^{ sharedInstance = [[self alloc] init]; }
 return sharedInstance;