Created
November 27, 2013 10:40
-
-
Save sag333ar/7673727 to your computer and use it in GitHub Desktop.
An Objective-C CSV Parser which works with ' (single-quote) or/and " (double-quote) on iOS 7 + iOS 6 + iOS 5 + iOS 4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (NSMutableArray *)loadAndParseWithStringData:(NSString*)stringData hasHeaderFields:(BOOL)hasHeaderFields{ | |
NSArray *gcRawData = [stringData componentsSeparatedByString:@"\n"]; | |
NSArray *singleGC = [NSArray array]; | |
NSMutableArray *allGC = [NSMutableArray array]; | |
for (int i = 0; i < gcRawData.count; i++) | |
{ | |
NSString *nextGCString = [NSString stringWithFormat:@"%@", gcRawData[i]]; | |
singleGC = [nextGCString componentsSeparatedByString:@","]; | |
NSMutableArray *arrayOfComponents = [NSMutableArray array]; | |
for (int j=0; j<singleGC.count; j++) { | |
NSString *str = [singleGC objectAtIndex:j]; | |
if([str hasPrefix:@"\""]) { | |
for (int k=j+1; k<singleGC.count; k++) { | |
str = [str stringByAppendingFormat:@",%@",[singleGC objectAtIndex:k]]; | |
j++; | |
if([str hasSuffix:@"\""] || [str hasSuffix:@"\"\r"]) { | |
break; | |
} | |
} | |
} else if([str hasPrefix:@"\'"]) { | |
for (int k=j+1; k<singleGC.count; k++) { | |
str = [str stringByAppendingFormat:@",%@",[singleGC objectAtIndex:k]]; | |
j++; | |
if([str hasSuffix:@"\'"] || [str hasSuffix:@"\'\r"]) { | |
break; | |
} | |
} | |
} | |
[arrayOfComponents addObject:str]; | |
} | |
[allGC addObject:arrayOfComponents]; | |
} | |
if(hasHeaderFields) { | |
NSArray *arrayOfHeader = [allGC objectAtIndex:0]; | |
NSMutableArray *newDataArray = [NSMutableArray array]; | |
for (NSArray *ar in allGC) { | |
if([ar isEqual:arrayOfHeader]) continue; | |
if(ar.count!=arrayOfHeader.count) continue; | |
NSMutableDictionary *dOfRow = [NSMutableDictionary dictionary]; | |
for (NSString *strHeaderName in arrayOfHeader) { | |
[dOfRow setObject:[ar objectAtIndex:[arrayOfHeader indexOfObject:strHeaderName]] forKey:strHeaderName]; | |
} | |
[newDataArray addObject:dOfRow]; | |
} | |
return newDataArray; | |
} | |
return allGC; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment