I have the following code in place:
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 (@"E开发者_高级运维lement %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'm trying to select specific objects from my database, anything with a waypoint_map_id of 98, but the NSPredicate is not working as I expected. Zero objects are getting selected.
Anyone any thoughts ?
The predicate with format does not covert the string "98" to a number. Instead it does
waypoint_map_id == "98"
... which is looking for string attribute. Change the predicate to:
NSInteger mapIdx=98;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"waypoint_map_id==%d", mapIDx];
... which returns a predicate of:
waypoint_map_id == 98
Assuming that you definately have that object in your database, try adding quotes around the value?
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"waypoint_map_id==\"%@\"", mapIDx];
(clutching at straws!)
Your prediacte looks fine so I would instantly start to suspect the bug is somewhere else :
- Is there definintely a waypoint with that id?
- Is listArray nil i.e. something else has gone wrong with the request?
You don't check to see what the error is - perhaps that will give you more information?
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];
Hope that's helpful at all!
Problem solved:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"waypoint_map_id contains[cd] %@", mapIDx];
[request setPredicate:predicate];
精彩评论