- /*
- NSArray toSentence
- ------------------
- If we have an array of strings like
- NSArray *myArray = [NSArray arrayWithObjects: @"home", @"work", @"holiday", @"unknown", nil];
- using this category, you can output it in a nice format using a single call.
- NSString *output = [myArray toSentence:];
- The default call with no options (toSentence:) will return this string:
- "home, work, holiday and unknown"
- The default word connector being "," and the last word connector being "and". We can override these
- default connectors by passing a dictionary to the toSentence call.
- NSDictionary *outputOptions = [NSDictionary dictionaryWithObjectsAndKeys:
- @" or ", @"wordConnector",
- @" then ", @"lastWordConnector", nil];
- NSString *output = [myArray toSentence: outputOptions];
- This call with options (toSentence: outputOptions) will return this string:
- "home or work or holiday then unknown"
- */
- @interface NSArray(mutableArrayExtensions)
- -(id)toSentence:(NSDictionary *)options;
- @end
- #import "NSArray+outputHelpers.h"
- //see header file for usage
- @implementation NSArray(mutableArrayExtensions)
- -(id)toSentence:(NSDictionary *)options{
- //initialize the temp string with the first string object in self
- NSMutableString *tempString = [NSMutableString stringWithFormat:@"%@", [self objectAtIndex:0]];
- //get our options or set the defaults
- NSString *lastWordConnector = [options objectForKey:@"lastWordConnector"] ? [options objectForKey:@"lastWordConnector"] : @" and ";
- NSString *wordConnector = [options objectForKey:@"wordConnector"] ? [options objectForKey:@"wordConnector"] : @", ";
- //connect the first upto but not-including the last object
- int i;
- for(i=1;i<self.count-1;i++){
- [tempString appendFormat:@"%@%@", wordConnector, [self objectAtIndex:i]];
- }
- //now append the last object
- [tempString appendFormat:@"%@%@", lastWordConnector, [self lastObject]];
- return tempString;
- }
- @end