soleil
soleil

Reputation: 13085

Core Data fault frustration

In a view controller (Tab 1), I load from core data like this:

- (void)loadRecordsFromCoreData {

[self.managedObjectContext performBlockAndWait:^{
    NSError *error = nil;
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Item"];
    [request setSortDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"order" ascending:YES]]];

    self.items = [self.managedObjectContext executeFetchRequest:request error:&error];

}];
}

I then display the items like this (in viewDidAppear):

- (void)displayItems
{
for(UIView *subview in [self.itemRow subviews]) {
    [subview removeFromSuperview];
}

int xPos = kXItemOffsetIphone;

for (Item *item in self.items) {
    ItemView *itemView = [[ItemView alloc] initWithFrame:CGRectMake(xPos, kYItemOffsetIphone, kItemWidthIphone, kItemHeightIphone) ];

    [itemView layoutWithData:item];

    [self.itemRow addSubview:itemView];

    xPos += kXItemSpacingIphone;
}

}

ItemView is a UIView subclass that displays the image associated with the item, etc. When I first run the app, all the items are displayed. However, if I click on another Tab, then come back to Tab 1, all my items disappear. The item array is still there, but each item in the array is a "fault", so nothing gets displayed. Very frustrating. How can I prevent these Items from becoming "faults"?

Upvotes: 2

Views: 1004

Answers (1)

Jack Lawrence
Jack Lawrence

Reputation: 10772

It sounds like your NSManagedObjectContext is getting deallocated (maybe your view controller is getting unloaded/cleaning itself up when you switch tabs?).

Behind the scenes, your objects are just proxies for data moving in and out of your SQLite store and between a cache managed by the NSManagedObjectContext. When the context is deallocated, the proxy objects still exist (hence why your array is still filled with objects) however they are unable to ask the deallocated managed object context for data and all of their values revert to faults.

You have a few options:

You can pass around a reference to your NSManagedObjectContext as you move between controllers so that you don't lose it.

You could re-fetch your data in -viewWillAppear: or another method that you find convenient that is fired every time your view is displayed.

You could also move your NSManagedObjectContext to a singleton object that exists for the lifetime of the application, however that can become brittle if you're not careful.

Upvotes: 4

Related Questions