简体   繁体   中英

Why does [context executeFetchRequest: request error: &error] fail to get data sometimes when the data I need exist?

In my app, I use Core Data foundation to store my data (some images). I need to fetch images from my data base and display them in a table view. When my app is loading, it will fetch some images from database. However, I am quite confused that sometimes the method

[context executeFetchRequest: request error: &error] 

would fail to fetch data from my database while sometimes it works well (I am quite sure the data is indeed in the database). I add some test code here:

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"Album" inManagedObjectContext:context]];
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"number" ascending:YES];
    request.sortDescriptors = @[sortDescriptor];    
    NSArray *matches = [context executeFetchRequest:request error:&error];

    for (int i = 0; i < 10; i++) {
        if ([matches count]) {
            break;
        }
        matches = [context executeFetchRequest:request error:&error];
        NSLog(@"try one more fetch for my data");
    } 

If the database is empty, the loop will exist after trying 10 times. But when my database is not empty, from NSLog method, I find that sometimes it fetched data successfully after trying 2 times and sometimes after 5 times, and sometimes after trying 10 times it still failed to fetch data. To be more specific, this phenomenon only happens when the first few [context executeFetchRequest: request error: &error] get executed. After that, the method works well.

So I want to know why does this happen, can anyone help me?

Your question is very generic. You should add details (what do you mean with fail, share your model, share the fetch request, etc)

Few tips here.

First of all executeFetchRequest:error: takes an error as param. So you have check it for errors.

NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
    // log error here
} else {
    // log results here
}

Second, if you are using a SQLite persistent store you can see logs Core Data creates in the following way: XCode4 and Core Data: How to enable SQL Debugging .

Finally, if you are using a SQLite persistent you can also inspect saved data. A possible path could be:

/Users/NAME/Library/Application Support/iPhone Simulator/VERSION/Applications/APP ID/Documents/DB FILE.sqlite

In addition to Dan Shelly's comment, are you performing any background operation to display images?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM