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) {
 block();
 } 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;