Remove leading and trailing spaces

March 10, 2013 in iOS Snippets

Removing start and end spaces of an NSString is very simple:

NSString* result = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

Converting an integer in a string into an NSNumber

March 10, 2013 in iOS Snippets

This new idiom is concise and clean:

NSNumber* intNumber = @([str intValue]);

Synchronous dispatch without deadlocking

March 4, 2013 in iOS Snippets

Dispatches synchronously without deadlocking if the target thread is the current thread.

static inline void dispatch_sync2(dispatch_queue_t queue, dispatch_block_t block) {
 if (dispatch_get_current_queue() == queue) {
 } else {
 dispatch_sync(queue, block);

NSMutableString to NSString

March 4, 2013 in iOS Snippets

Method 1, making a copy:

NSString* str = [mutableStr copy];

Method 2, also making a copy:

NSString* str = [NSString stringWithString:mutableStr];

Method 3, passing the original mutable string as an NSString by casting (almost never used):

NSString* immutableRefToMutableString = (NSString*)mutableStr;

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;