NSPredicate - not working as expected

I have the following code:

    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];

As you can see, I am trying to select specific objects from my database, anything with waypoint_map_id from 98, but NSPredicate does not work as I expected. Zero objects are selected.

Any thoughts?

+3
source share
3 answers

A format predicate does not hide the string "98" to a number. Instead he does

waypoint_map_id == "98"

... which searches for the string attribute. Change the predicate to:

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

... which returns the predicate:

waypoint_map_id == 98
+6
source

Assuming you definitely have this object in your database, try adding quotes around the value?

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

(clutching a straw!)

prediacte , , - :

  • ?
  • listArray nil i.e, - ?

, - , ?

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

Problem resolved:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"waypoint_map_id contains[cd] %@", mapIDx];
    [request setPredicate:predicate];
+1
source

Source: https://habr.com/ru/post/1755940/


All Articles