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]);

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;

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.

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);

}