将数据从csv文件加载到xcode时,NSString无法正确显示

时间:2011-01-26 18:07:49

标签: iphone xcode

我有一个存储3个值的csv文件 - 城市名称以及州,经度和纬度值。

我用excel打开时出现的示例数据将是:Boston,Mass。,411.932,73

我面临的第一个问题是,当我将csv文件复制到xcode项目文件夹时,xcode将文件数据显示为“Albany,N.Y。”,397.898,73,并在第一列数据中添加“”。

我面临的第二个问题是,当我从csv文件中检索数据并将城市名称作为NSString时,该字符串仅显示Albany而不是Albany,N.Y。

这就是我的所作所为。谢谢你的帮助。

NSString* filePath = [[NSBundle mainBundle] pathForResource:@"citiesdataUsed" ofType:@"csv"];
NSString* fileContents =  [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

NSArray* pointStrings = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
cityList = [[NSMutableArray alloc]init];

//skip line 0 as it is the title of each column
for(int idx = 0; idx < pointStrings.count; idx++)
{
    Pair *sth = [[Pair alloc] init];
    // break the string down even further to the columns. 
    NSString* currentPointString = [pointStrings objectAtIndex:idx];
    NSArray* arr = [currentPointString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]];

    NSString *country = [[NSString alloc] initWithFormat:@"%@", [arr objectAtIndex:0]];
    NSNumber *latData = [[NSNumber alloc]  initWithFloat:[[arr objectAtIndex:2] floatValue]]; //long
    NSNumber *longData = [[NSNumber alloc]  initWithFloat:[[arr objectAtIndex:1] floatValue]]; //lat

    //convert the NSNumbers to float value
    float longData2 = [longData floatValue];
    float latData2 = [latData floatValue];
    CGPoint temp = CGPointMake(longData2,latData2);
    sth.city = country;
    sth.location = temp;
    [cityList addObject: sth];
    [sth release];
}

1 个答案:

答案 0 :(得分:0)

关于你的国家只解析第一部分..

您要按,拆分该行,因此您的数组看起来像

arr[0] = Albany
arr[1] = N.Y.
arr[2] = 397.898
arr[3] = 73

您的代码应显示为

NSString *country = [[NSString alloc] initWithFormat:@"%@, %@", [arr objectAtIndex:0], [arr objectAtIndex:1]];
NSNumber *latData = [[NSNumber alloc]  initWithFloat:[[arr objectAtIndex:2] floatValue]]; //long
NSNumber *longData = [[NSNumber alloc]  initWithFloat:[[arr objectAtIndex:3] floatValue]]; //lat

不太清楚为什么xcode会在CSV文件中包含引号但是如果引号只显示在xcode而不是(例如)textedit中,那么您的文件就可以了。