我尝试通过解析.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值吗?我怎么解决它?提前感谢您的时间。
答案 0 :(得分:2)
您已定义字典键:
#define kStation @"station"
#define kLatitude @"latitude"
#define kLongitude @"longitude"
尝试:
NSDictionary *dict = @{kLatitude : @(latitude),
kLongitude: @(longitude),
kStation : station};
您在第一个阵列创建中使用它们,但在第二个阵列中不使用它们。
答案 1 :(得分:1)
试用此代码,
1)处理您定义的键总是更好,
2)在获取double值之前,请确保该字符串中没有空格和换行符
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];
}