-2

我试图通过解析一个 .csv 文件来创建一个数组然后我通过这个函数运行它。

//Array

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

NSArray *locations = [csvString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

NSMutableArray *secondArray = [NSMutableArray array];
for (NSString * location in locations)
{

NSArray *components = [location componentsSeparatedByString:@","];

double latitude   = [components[0] doubleValue];
double longitude  = [components[1] doubleValue];
NSString *station =  components[2];

NSDictionary *dict = @{@"kLatitude": @(latitude),
                       @"kLongitude": @(longitude),
                       @"kStation": station};

[secondArray addObject:dict];

}

//Comes Out

secondArray = (
    {
    kLatitude = "41.656467";
    kLongitude = "-81.277963";
    kStation = 27200;
},
    {
    kLatitude = "41.657118";
    kLongitude = "-81.276545";
    kStation = 27650;
},
    {
    kLatitude = "41.658493";
    kLongitude = "-81.27354200000001";
    kStation = 28632;
}...


//function

NSArray *orderedPlaces = [locationsArray sortedArrayUsingComparator:^(id a,id b) {

NSDictionary *dictA;
NSDictionary *dictB;
CLLocation *locA;
CLLocation *locB;

dictA = (NSDictionary *)a;
dictB = (NSDictionary *)b;
locA = [[CLLocation alloc] initWithLatitude:[[dictA objectForKey:kLatitude] doubleValue]longitude:[[dictA objectForKey:kLongitude] doubleValue]];
locB = [[CLLocation alloc]
        initWithLatitude:[[dictB objectForKey:kLatitude] doubleValue]
        longitude:[[dictB objectForKey:kLongitude] doubleValue]];

问题是该函数无法识别数组值。我想这与我如何定义值有关。具体来说,调用 kLatitude 和 kLongitude。

有人可以确定为什么我的函数不像读取 firstArray 值那样读取 secondArray 值吗?我该如何解决?提前感谢您的时间。

4

2 回答 2

2

您已经定义了字典键:

#define kStation @"station"
#define kLatitude @"latitude"
#define kLongitude @"longitude"

尝试:

NSDictionary *dict = @{kLatitude : @(latitude),
                       kLongitude: @(longitude),
                       kStation  : station};

您在第一次创建数组时使用它们,但在第二次创建时不使用它们。

于 2013-05-14T02:19:23.483 回答
1

试试这个代码,

1)处理您定义的键总是更好,
2)在获取双值之前,请确保该字符串中没有空格和换行符

NSCharacterSet *whiteSPNewLine = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    for (NSString * location in locations)
    {

        NSArray *components = [location componentsSeparatedByString:@","];

        double latitude   = [[components[0] stringByTrimmingCharactersInSet:whiteSPNewLine] doubleValue];
        double longitude  = [[components[1] stringByTrimmingCharactersInSet:whiteSPNewLine] doubleValue];
        NSString *station = [components[2] stringByTrimmingCharactersInSet:whiteSPNewLine];

        NSDictionary *dict = @{kLatitude: @(latitude),
                               kLongitude: @(longitude),
                               kStation: station};

        [secondArray addObject:dict];

    }
于 2013-05-14T03:01:46.547 回答