我正在寻找一个易于在iPhone上使用的Objective-C CSV解析器。您知道在哪里可以找到吗?
我还在寻找其他解析器,例如JSON,也许有转换库可以用。
我正在寻找一个易于在iPhone上使用的Objective-C CSV解析器。您知道在哪里可以找到吗?
我还在寻找其他解析器,例如JSON,也许有转换库可以用。
我终于抽出时间整理了一个解析器,将其发布在Github上:http://github.com/davedelong/CHCSVParser
它相当全面。它处理各种转义方案、字段中的换行符、注释等等。此外,它还使用智能文件加载,这意味着您可以在内存受限的情况下安全地解析大型文件。
这是一个简单的NSString类别,用于解析包含在引号块内的逗号的CSV字符串。
#import "NSString+CSV.h"
@implementation NSString (CSV)
- (NSArray *)componentsSeparatedByComma
{
BOOL insideQuote = NO;
NSMutableArray *results = [[NSMutableArray alloc] init];
NSMutableArray *tmp = [[NSMutableArray alloc] init];
for (NSString *s in [self componentsSeparatedByString:@","]) {
if ([s rangeOfString:@"\""].location == NSNotFound) {
if (insideQuote) {
[tmp addObject:s];
} else {
[results addObject:s];
}
} else {
if (insideQuote) {
insideQuote = NO;
[tmp addObject:s];
[results addObject:[tmp componentsJoinedByString:@","]];
tmp = nil;
tmp = [[NSMutableArray alloc] init];
} else {
insideQuote = YES;
[tmp addObject:s];
}
}
}
return results;
}
@end
这个假设您已经将CSV文件读入数组中:
myArray = [myData componentsSeparatedByString:@"\n"];
该代码未考虑转义引号,但很容易进行扩展。
NSString *dataStr = [NSString stringWithContentsOfFile:@"example.csv" encoding:NSUTF8StringEncoding error:nil];
NSArray *array = [dataStr componentsSeparatedByString: @","];
好的,上述简单解决方案并没有考虑到多条记录。使用以下代码读取默认的Excel CSV,并使用ASCII 13作为行结束标记:
NSString *content = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:nil];
NSArray *contentArray = [content componentsSeparatedByString:@"\r"]; // CSV ends with ACSI 13 CR (if stored on a Mac Excel 2008)
for (NSString *item in contentArray) {
NSArray *itemArray = [item componentsSeparatedByString:@";"];
// log first item
NSLog(@"%@",[itemArray objectAtIndex:0]);
}
这似乎是我目前找到的最全面的。
http://www.macresearch.org/cocoa-scientists-part-xxvi-parsing-csv-data
作为一个旁注,你会认为大多数主要的编程语言(如Delphi、C#、Objective-c、php等)都应该有一个可用的库,其中包含了这种基本数据交换格式的完整实现。几周前我发现了ParseKit
但在我看来,对于大多数情况来说,-[NSString componentsSeparatedByString:]
方法和NSScanner
已经足够并且非常容易使用。
NSArray* items;
items=[bufferString componentsSeparatedByString:@","];
NSString* fileName = @"Level";
fileName = [fileName stringByAppendingString:levelNumberBeingEdited];
fileName = [fileName stringByAppendingString:@".txt"];
NSString* bufferString=@"";
通过循环遍历每个数据项(未显示)并在它们之间插入逗号,填充缓冲字符串。最后导出。
NSString* homeDir = NSHomeDirectory();
NSString* fullPath = [homeDir stringByAppendingPathComponent:fileName];
NSError* error = nil;
[bufferString writeToFile:fullPath atomically:NO encoding:NSASCIIStringEncoding error:&error];
#import "CHCSV.h"
。 - Dave DeLong