【发布时间】:2015-02-12 00:11:39
【问题描述】:
我正在尝试一个小项目,获取当前位置坐标,然后通过当前位置找到附近的咖啡店并将它们显示在 UITableView 中。到目前为止,我已经成功地加载了包含信息的 JSON 脚本,将其解析为字典,并将其显示在 UITableView 中。我现在想做的是尝试按“距离”或“名称”(按字母顺序)排序信息。我怎样才能做到这一点?这是一些代码来展示我到目前为止所做的事情。
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
if (!self.didFindLocation) {
self.didFindLocation = YES;
[self.locationManager stopUpdatingLocation];
}
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
CLLocation *crnLoc = [locations lastObject];
NSString *latitudeString = [NSString stringWithFormat:@"%.10f",crnLoc.coordinate.latitude];
NSString *longitudeString = [NSString stringWithFormat:@"%.10f",crnLoc.coordinate.longitude];
NSString *urlString = [NSString stringWithFormat:@"https://api.foursquare.com/v2/venues/search?client_id=ACAO2JPKM1MXHQJCK45IIFKRFR2ZVL0QASMCBCG5NPJQWF2G&client_secret=YZCKUYJ1WHUV2QICBXUBEILZI1DMPUIDP5SHV043O04FKBHL&ll=%@,%@&query=coffee&v=20140806&m=foursquare", latitudeString, longitudeString];
NSURL *url = [NSURL URLWithString:urlString];
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *responseDictionary = [dataDictionary objectForKey:@"response"];
NSDictionary *venueDictionary = [responseDictionary objectForKey:@"venues"];
for (NSDictionary *dict in venueDictionary) {
NSString *name = [dict objectForKey:@"name"];
NSDictionary *locationDictionary = [dict objectForKey:@"location"];
NSString *address = [NSString stringWithFormat: @"%@", [locationDictionary objectForKey:@"address"]];
if (address == nil) {
address = @"No address provided";
}
NSString *distance = [NSString stringWithFormat: @"%@", [locationDictionary objectForKey:@"distance"]];
if (distance == nil) {
distance = @"No coordinates provided";
}
NSLog(@"Name: %@ Address: %@ distance: %@", name, address, distance);
CoffeeStore *store = [[CoffeeStore alloc] initWithName:name address:address distance:distance];
[resultArray addObject:store];
}
self.storeArray = resultArray;
[self.tableView reloadData]; }
和
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
CoffeeStore *selectedStore = self.storeArray[indexPath.row];
cell.textLabel.text = selectedStore.name;
cell.detailTextLabel.text = selectedStore.distanceString;
return cell;
}
【问题讨论】:
-
您听说过 NSSortDescriptor 吗?
-
另外,
NSData方法dataWithContentsOfURL是同步的,我认为您正在主线程上运行它。您确实需要将其移至后台线程,然后在获取数据后再次获取主线程。
标签: ios objective-c json uitableview nsdictionary