开发者

Searching for an id in Core Data

开发者 https://www.devze.com 2023-03-15 05:13 出处:网络
I am getting some unexpected behavior with CoreData and NSPredicate. In a large database population I have different Managed Objects relating to on开发者_C百科e-another. However, I have a problem with

I am getting some unexpected behavior with CoreData and NSPredicate. In a large database population I have different Managed Objects relating to on开发者_C百科e-another. However, I have a problem with the following. When giving an id (NSNumber, given as NSString to this function) I don't get a result unless I save the whole context first. I don;t want to do that as it takes too much time (as it is a large set of data). The code is:

- (DOSite *) findSite:(NSString *) siteId {
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"(id = %@)", siteId];

    [NSFetchedResultsController deleteCacheWithName:nil];
    [[self fetchedResultsController].fetchRequest setPredicate:predicate];

    NSError *fetchError;

    if (![[self fetchedResultsController] performFetch:&fetchError]) {
        // Handle the error.
        // This is a serious error and should advise the user to restart the application
        NSLog(@"Fetching data error: %@", [fetchError localizedDescription]);
    }

    if([[[self fetchedResultsController] fetchedObjects] count] == 0){
        return NULL;
    }
    return (DOSite *)[[[self fetchedResultsController] fetchedObjects] objectAtIndex:0];
}

So when I add an x number of items (using +[NSEntityDescription insertNewObjectForEntityForName:inManagedObjectContext:]) doing a search on all items return the right amount of items.

When searching for a string (e.g.predicateWithFormat:@"(name LIKE %@)") I get positive results, but when using the above code predicateWithFormat:@"(id = %@) I get zero results.

The only way I can get results is to save the whole context and then perform the fetchRequest, then suddenly it works.

So there must be something small I do wrong in searching for the id, I just seem to be blind to find it and spend two days at it now to narrow it down to this point. Is there anybody who can give me some advice on this?


This may not work, but have you tried using a name more complex than "id" in your entity (like "SiteID")? Sometimes very short names overlap with other system properties and it causes odd issues.


The problem was that I gave a NSString to the predicate as outlined above. When changing that to an int (ie predicateWithFormat:@"(id == %i)") it works fine for some reason.

0

精彩评论

暂无评论...
验证码 换一张
取 消