浮点数的核心数据谓词过滤

时间:2011-08-03 15:02:24

标签: iphone ios core-data nspredicate

基本上,我有一个MKMapView的位置数据库,当点击每个注释上的详细信息披露按钮时,它会显示有关该位置的更多信息,例如他们的网站和电话号码。

问题是,在我的数据库中,一些坐标只有4或5个小数而不是6,所以当点击按钮时,应用程序会崩溃。 为了阻止这种情况,我在UIAlertView中添加了“我们无法找到更多信息” 有没有办法以更好的方式使用我的谓词?

NSString *lat = [NSString stringWithFormat:@"%.6f", view.annotation.coordinate.latitude];
NSString *lon = [NSString stringWithFormat:@"%.6f", view.annotation.coordinate.longitude];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Stores" inManagedObjectContext:_managedObjectContext];
[request setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Latitude == %@ && Longitude == %@", lat, lon];
[request setPredicate:predicate];

NSError *error = nil;
NSArray *stores = [_managedObjectContext executeFetchRequest:request error:&error];
[request release];
if (![stores count]) {
    UIAlertView *alert = [[[UIAlertView alloc]initWithTitle:@"Error" message:@"Sorry, we are unable to locate more information for this location." delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles: nil]autorelease];
    [alert show];
 } else {



    Stores *currentStore = [stores objectAtIndex:0];
    NSLog(@"current store %@", currentStore);

    AddressAnnotation *annotation = view.annotation;

    MoreInfoTable *moreInfoView = [[MoreInfoTable alloc] initWithStyle:UITableViewStyleGrouped];
    moreInfoView.currentStore = currentStore;
    moreInfoView.managedObjectContext = self.managedObjectContext;
    moreInfoView.title = annotation.title ;
    moreInfoView.getWebsite =[NSURL URLWithString:annotation.website];
    moreInfoView.getDirections = [NSURL URLWithString:[NSString stringWithFormat:@"http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f", mapView.userLocation.coordinate.latitude, mapView.userLocation.coordinate.longitude, annotation.coordinate.latitude, annotation.coordinate.longitude]];
    moreInfoView.footer = [NSString stringWithFormat:@"%.1f miles away", annotation.distanceFromLocation];
    moreInfoView.address = annotation.address;
    moreInfoView.getPhoneNumber = [NSMutableString stringWithString:annotation.phoneNumber];
    moreInfoView.lat = view.annotation.coordinate.latitude;
    moreInfoView.lon = view.annotation.coordinate.longitude;

    [self.navigationController pushViewController:moreInfoView animated:YES];
    [moreInfoView release]; 

}

}

1 个答案:

答案 0 :(得分:1)

我假设您正在尝试获得所有具有纬度或经度的商店实体。您应该检查纬度或经度!= nil,而不是与您的6位十进制字符串进行比较。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Latitude != nil && Longitude != nil"];
[request setPredicate:predicate];