8

对于我的新项目。我已将我的 csv 文件内容加载为 NSString。首先,我需要用换行符分割它,然后用逗号分割每一行。我怎样才能循环这一切?请你帮助我好吗?

CSV 内容

"^GSPC",1403.36,"4/27/2012","4:32pm",+3.38,1400.19,1406.64,1397.31,574422720 "^IXIC",3069.20,"4/27/2012","5:30pm ",+18.59,3060.34,3076.44,3043.30,0

视图控制器.m

NSString* pathToFile = [[NSBundle mainBundle] pathForResource: @"quotes" ofType: @"csv"];
NSString *fileString = [NSString stringWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:nil];
if (!fileString) {
    NSLog(@"Error reading file.");
}

NSArray *array = [fileString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

for(int i=0; i<[array count]; i++){      
    //
}
4

1 回答 1

13

可能想调查一下NSMutableArray

// grab your file
NSMutableArray *data = [[fileString componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]] mutableCopy];
for (int i = 0; i < [data count]; i++)
{
    [data replaceObjectAtIndex: i
                    withObject: [[data objectAtIndex: i] componentsSeparatedByString: @","]];
}

相关地,Dave DeLong 有一个适当的库来满足这一需求:https ://github.com/davedelong/CHCSVParser

于 2012-04-29T07:47:50.237 回答