Fetch Is Crashing App on ViewDidLoad
In my viewDidLoad
, I have self.todaySession = (id)[fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSect开发者_运维问答ion:0]];
which works fine when it finds this object. But when it doesn't, it crashes the app. Is there a logic statemnt I can do to fix this?
There are a few ways of doing this depending on the context.
You can use the count of fetchedObjects
or sections
from the NSFetchedResultsController
. Make sure you call performFetch:
beforehand.
[fetchedResultsController performFetch:self];
// Option 1
BOOL someResultsReturned = ([[fetchedResultsController fetchedObjects] count] > 0);
// Option 2
BOOL someResultsReturned = ([[fetchedResultsController sections] count] > 0);
if (someResultsReturned) {
self.todaySession = (id)[fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
} else {
// Handle no results here
}
More Information
Read more about NSFetchedResultsController here.
精彩评论