NSManagedObjectContext nil当调用第二次 [英] NSManagedObjectContext nil when calling second time

查看:107
本文介绍了NSManagedObjectContext nil当调用第二次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我想多次访问Core Data时,都会出现错误。我有一个表视图,我试图接收数据并显示它。



我的SecondViewController.h中有一个变量:

  #import< UIKit / UIKit.h> 
#importCooperTestModel.h
#importEvent.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

和SecondViewController.m

  #importSecondViewController.h

@implementation SecondViewController
@synthesize managedObjectContext,eventArray;



在我的AppDelegate中,我得到一个对象设置为我的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。返回新实例。
return managedObjectContext;
}

然后我正在抓取tableView中的数据:

   - (void)fetchRecords {

NSLog(@Fetching records。
//定义我们的表/实体使用
NSEntityDescription * entity = [NSEntityDescription entityForName:@EventinManagedObjectContext:managedObjectContext];
//设置获取请求
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
//定义如何对记录进行排序
NSSortDescriptor * sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@timeStampascending:NO];
NSArray * sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[request setSortDescriptors:sortDescriptors];
//获取记录并处理错误
NSError * error;
NSMutableArray * mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:& error] mutableCopy];
if(!mutableFetchResults){
NSLog(@获取数据错误。
}
//将我们获取的数据保存到数组
[self setEventArray:mutableFetchResults];

NSLog(@找到的记录:%i,[eventArray count]);
}

这适用于第一次尝试,但是, :

  2013-09-07 19:55:03.715 CooperTest [2697:11603] managedObjectContext nil。返回新实例。 
2013-09-07 19:55:03.729 CooperTest [2697:11603]获取记录。
2013-09-07 19:55:03.732 CooperTest [2697:11603]找到的记录:3
2013-09-07 19:55:03.734 CooperTest [2697:11603]表中的行:3
2013-09-07 19:55:04.874 CooperTest [2697:11603]获取记录。
2013-09-07 19:55:04.878 CooperTest [2697:11603] ***由于未捕获异常NSInvalidArgumentException终止应用程序,原因:'+ entityForName:nil不是合法的NSManagedObjectContext参数搜索实体名称'Event''
libc ++ abi.dylib:terminate调用抛出异常

想法呢?我没有设置一个新的项目,并勾选了使用核心数据选项,因为它不在那里。所以我在AppDelegate中添加了CoreData.framework和一些代码。此外,模型和类都有正确的(我能够在 fetchRecords 结尾存储3个记录)。

修复它。

  AppDelegate * appDelegate =(AppDelegate * )[[UIApplication sharedApplication] delegate]; 
managedObjectContext = appDelegate.managedObjectContext;在ViewControlelr中的

,而不是从AppDelegate传递。


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).

解决方案

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.

这篇关于NSManagedObjectContext nil当调用第二次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆