Skip to content

Instantly share code, notes, and snippets.

@Megatron1000
Created October 15, 2013 19:49
Show Gist options
  • Save Megatron1000/6997590 to your computer and use it in GitHub Desktop.
Save Megatron1000/6997590 to your computer and use it in GitHub Desktop.
Category for NSString that can turn an array of strings into a list with comas and an and at the end.
//
// NSString+ArrayWriter.h
// Attributed String Creator
//
// Created by Mark Bridges on 15/10/2013.
// Copyright (c) 2013 Mark Bridges. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSString (ArrayWriter)
+ (NSString*)stringWithArray:(NSArray*)array;
@end
//
// NSString+ArrayWriter.m
// Attributed String Creator
//
// Created by Mark Bridges on 15/10/2013.
// Copyright (c) 2013 Mark Bridges. All rights reserved.
//
#import "NSString+ArrayWriter.h"
@implementation NSString (ArrayWriter)
+ (NSString*)stringWithArray:(NSArray*)array{
if (array.count == 0) {
return @"";
}
else{
NSMutableString *outputString = [[NSMutableString alloc]init];
NSMutableArray *mutableArray = [[NSMutableArray alloc]initWithArray:array];
if (mutableArray.count == 1) {
[outputString appendString:[mutableArray objectAtIndex:0]];
}
else{
[outputString appendString:[mutableArray objectAtIndex:0]];
[mutableArray removeObjectAtIndex:0];
for (NSString *currentString in mutableArray) {
if (currentString != mutableArray.lastObject) {
[outputString appendString:[NSString stringWithFormat:@", %@",currentString]];
}
else{
[outputString appendString:[NSString stringWithFormat:@" and %@.",currentString]];
}
}
}
return outputString;
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment