Deleting all entities

February 27, 2013 in iOS Snippets

The following code simply fetches and deletes all objects of a given entity name – just remember to save the changes afterwards.

+ (void)deleteAllEntities:(NSString*)name inContext:(NSManagedObjectContext*)context;
  NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init];
  [fetchRequest setEntity:[NSEntityDescription entityForName:name inManagedObjectContext:context]];
  NSArray* fetchResult = [context executeFetchRequest:fetchRequest error:nil];
  for (id obj in fetchResult) {
    [context deleteObject:obj];

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.

Running code on the UI thread

February 27, 2013 in iOS Snippets

As an iOS developer you’ll get to see this all the time, since you have to be enormously careful when running code that does any UI processing; such code must always run in the main (UI) thread, so when running on a different thread it’s necessary to pass a block of code to be executed by the main thread:

dispatch_async(dispatch_get_main_queue(), ^{

// ... code to execute in main thread ...


dispatch_async() will run that code right away, asynchronously – ie, it will not wait to queue the code into the main queue. Use dispatch_sync() if you want to wait until it’s done – but be careful! If you target the current queue, it will result in a deadlock. More information in the official documentation.

Helper method to convert an NSDate to string

February 26, 2013 in iOS Snippets

For performance reasons we only create the formatter object once, and just reuse it afterwards. The formatter style can be easily tailored by duplicating the method and changing its options; we keep the method’s name as descriptive as possible of the conversion to be done. It is also a good idea to keep this in a category on NSString.

+ (NSString*)dateAsFullDateTime:(NSDate*)date;
  static NSDateFormatter * formatter = nil;
  if (formatter == nil) {
    formatter = [[NSDateFormatter  alloc] init];
    [formatter setDateStyle:NSDateFormatterFullStyle];
    [formatter setTimeStyle:NSDateFormatterLongStyle];
    [formatter setDoesRelativeDateFormatting:NO];
  return [formatter stringFromDate:date];

URL Encoding an NSString

February 26, 2013 in iOS Snippets

+ (NSString*)urlEncodeString:(NSString*)str;


return (__bridge_transfer NSString *)

CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)str, NULL,
   (CFStringRef)@"!*'();:@&=+$,/?%#[ ]", kCFStringEncodingUTF8);


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;

Throwing an exception in iOS

February 26, 2013 in iOS Snippets

[NSException raise:@"Invalid parameter" format:@"Object %@ is incorrect", obj];

Clearing all notifications an object is observing

February 16, 2013 in iOS Snippets

[[NSNotificationCenter defaultCenter] removeObserver:self];


Clearing the selection of a table view

February 16, 2013 in iOS Snippets

[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];

How to easily tell if a device has access to the Internet

February 16, 2013 in iOS Snippets

Use this full-featured library: Reachability - an improved version of Apple’s classic Reachability code sample.