Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

ios - NSManagedObjectContext nil when calling second time

I have an an error everytime I want to access Core Data more than once. I have a table view, where I'm trying to receive data and display it.

I have a variable in my SecondViewController.h:

#import <UIKit/UIKit.h>
#import "CooperTestModel.h"
#import "Event.h"
#import <CoreData/CoreData.h>

@interface SecondViewController : UITableViewController {
    NSManagedObjectContext *managedObjectContext;
    NSMutableArray *eventArray;
}

@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, strong) NSMutableArray *eventArray;

- (void) fetchRecords;

@end

and SecondViewController.m

#import "SecondViewController.h"

@implementation SecondViewController
@synthesize managedObjectContext, eventArray;

In my AppDelegate I get an object which is set to my ViewController:

- (void)applicationDidFinishLaunching:(UIApplication *)application {

    SecondViewController *tableController = [[SecondViewController alloc] init];
    tableController.managedObjectContext = [self managedObjectContext];

    self.navigationController = [[UINavigationController alloc] initWithRootViewController:tableController];

    [window addSubview: [self.navigationController view]];
    [window makeKeyAndVisible];

}


- (NSManagedObjectContext *) managedObjectContext {

    if (managedObjectContext != nil) {
        NSLog(@"managedObjectContext already in use. Returning instance.");
        return managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        managedObjectContext = [[NSManagedObjectContext alloc] init];
        [managedObjectContext setPersistentStoreCoordinator: coordinator];
    }

    NSLog(@"managedObjectContext nil. Returning new instance.");
    return managedObjectContext;
}

Then I'm fetching the data in the tableView:

- (void)fetchRecords {

    NSLog(@"Fetching records.");
    // Define our table/entity to use
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext];
    // Setup the fetch request
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entity];
    // Define how we will sort the records
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    [request setSortDescriptors:sortDescriptors];
    // Fetch the records and handle an error
    NSError *error;
    NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (!mutableFetchResults) {
        NSLog(@"Error fetching data.");
    }
    // Save our fetched data to an array
    [self setEventArray: mutableFetchResults];

    NSLog(@"Records found: %i", [eventArray count]);
}

This works fine for the first attempt but then, I'm getting this error:

2013-09-07 19:55:03.715 CooperTest[2697:11603] managedObjectContext nil. Returning new instance.
2013-09-07 19:55:03.729 CooperTest[2697:11603] Fetching records.
2013-09-07 19:55:03.732 CooperTest[2697:11603] Records found: 3
2013-09-07 19:55:03.734 CooperTest[2697:11603] Rows in table: 3
2013-09-07 19:55:04.874 CooperTest[2697:11603] Fetching records.
2013-09-07 19:55:04.878 CooperTest[2697:11603] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Event''
libc++abi.dylib: terminate called throwing an exception

Any ideas on this? I did not setup a new project and ticked the "use core data" option, because it wasn't there. So I added the CoreData.framework and some Code in the AppDelegate. Also the Model and classes are there correct (I was able to store 3 records justa at the end of fetchRecords).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Finally I just fixed it by using

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
managedObjectContext = appDelegate.managedObjectContext;

in the ViewControlelr instead of passing it from AppDelegate.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...