Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 5th, 2012  |  syntax: None  |  size: 1.92 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. /*
  2.  NSArray toSentence
  3.  ------------------
  4.  If we have an array of strings like
  5.  
  6.  NSArray *myArray = [NSArray arrayWithObjects: @"home", @"work", @"holiday", @"unknown", nil];
  7.  
  8.  using this category, you can output it in a nice format using a single call.
  9.  
  10.  NSString *output = [myArray toSentence:];
  11.  
  12.  The default call with no options (toSentence:) will return this string:
  13.  "home, work, holiday and unknown"
  14.  
  15.  The default word connector being "," and the last word connector being "and". We can override these
  16.  default connectors by passing a dictionary to the toSentence call.
  17.  
  18.  NSDictionary *outputOptions = [NSDictionary dictionaryWithObjectsAndKeys:
  19.  @" or ", @"wordConnector",
  20.  @" then ", @"lastWordConnector", nil];
  21.  NSString *output = [myArray toSentence: outputOptions];
  22.  
  23.  This call with options (toSentence: outputOptions) will return this string:
  24.  "home or work or holiday then unknown"
  25.  */
  26. @interface NSArray(mutableArrayExtensions)
  27. -(id)toSentence:(NSDictionary *)options;
  28. @end
  29.  
  30. #import "NSArray+outputHelpers.h"
  31. //see header file for usage
  32.  
  33. @implementation NSArray(mutableArrayExtensions)
  34. -(id)toSentence:(NSDictionary *)options{       
  35.         //initialize the temp string with the first string object in self
  36.         NSMutableString *tempString = [NSMutableString stringWithFormat:@"%@", [self objectAtIndex:0]];
  37.        
  38.         //get our options or set the defaults
  39.         NSString *lastWordConnector = [options objectForKey:@"lastWordConnector"] ? [options objectForKey:@"lastWordConnector"] : @" and ";
  40.         NSString *wordConnector = [options objectForKey:@"wordConnector"] ? [options objectForKey:@"wordConnector"] : @", ";
  41.        
  42.         //connect the first upto but not-including the last object
  43.         int i;
  44.         for(i=1;i<self.count-1;i++){
  45.                 [tempString appendFormat:@"%@%@", wordConnector, [self objectAtIndex:i]];
  46.         }
  47.         //now append the last object
  48.         [tempString appendFormat:@"%@%@", lastWordConnector, [self lastObject]];
  49.         return tempString;
  50. }
  51. @end