NSPredicate - 未按预期工作

时间:2010-07-22 09:27:32

标签: iphone core-data

我有以下代码:

    NSString *mapIDx = @"98";
    NSLog(@"map id: %@", mapIDx);

    NSFetchRequest *request = [[NSFetchRequest alloc] init];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"WayPoint" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];

    //NSPredicate *predicate = [NSPredicate predicateWithFormat:@"waypoint_map_id=%@", mapIDx];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"waypoint_map_id==%@", mapIDx];
    [request setPredicate:predicate];

    NSError *error;
    listArray = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    [request release];


    int arrayItemQuantity = [listArray count];
    NSLog(@"Array Quantity: %d", arrayItemQuantity);

    // Loop through the array and display the contents.
    int i;
    for (i = 0; i < arrayItemQuantity; i++)
    {
        NSLog (@"Element %i = %@", i, [listArray objectAtIndex: i]);
    }

    /*
    NSInteger *xCoordinate = listArray[1];
    NSInteger *yCoordinate = listArray[3];
    NSLog(@"xCoordinate: %@", xCoordinate);
    NSLog(@"yCoordinate: %@", yCoordinate);

    CLLocationCoordinate2D coordinate = {xCoordinate, yCoordinate};
    MapPin *pin = [[MapPin alloc]initwithCoordinates:coordinate];
    [self.mapView addAnnotation:pin];
    [pin release];
    */

    [listArray release];

正如您所看到的,我正在尝试从我的数据库中选择特定对象,其中waypoint_map_id为98,但NSPredicate没有按预期工作。零对象正在被选中。

有人有什么想法吗?

3 个答案:

答案 0 :(得分:6)

格式的谓词不会将字符串“98”转换为数字。相反它确实

waypoint_map_id == "98"

...正在寻找字符串属性。将谓词更改为:

NSInteger mapIdx=98;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"waypoint_map_id==%d", mapIDx];

...返回谓词:

waypoint_map_id == 98

答案 1 :(得分:2)

假设您确定在数据库中拥有该对象,请尝试在值周围添加引号?

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"waypoint_map_id==\"%@\"", mapIDx];

(抓着稻草!)

你的预感看起来很好,所以我会立即开始怀疑这个错误在其他地方:

  • 这个id是否明确地是一个航点?
  • listArray是否为nil,即请求出现了其他问题?

您没有检查错误是什么 - 也许这会为您提供更多信息?

NSError *error = nil;
NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];
[request release];

if (nil == results || nil != error)
  NSLog(@"Error getting results : %@", error);

listArray = [results mutableCopy];

希望这对你有帮助!

答案 2 :(得分:1)