开发者

Fetch Is Crashing App on ViewDidLoad

开发者 https://www.devze.com 2023-03-24 14:14 出处:网络
In my viewDidLoad, I have self.todaySession = (id)[fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSect开发者_运维问答ion:0]]; which works fine when it finds this object.Bu

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.

0

精彩评论

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