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?