RestKit:“ NSInternalInconsistencyException”,原因:“无法执行映射:未分配“ managedObjectContext” [英] RestKit: 'NSInternalInconsistencyException', reason: 'Unable to perform mapping: No `managedObjectContext` assigned

查看:96
本文介绍了RestKit:“ NSInternalInconsistencyException”,原因:“无法执行映射:未分配“ managedObjectContext”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下错误:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Unable to perform mapping: No `managedObjectContext` assigned. (Mapping response.URL = https://www.someurl.com/lastrequest=2014-12-08T02%3A44%3A52Z)'

应用程序在RKResponseMapperOperation.m中的以下行停止:

The app stops at the following line in RKResponseMapperOperation.m:

- (RKMappingResult *)performMappingWithObject:(id)sourceObject error:(NSError **)error
{

    NSLog(@"managedObjectContext: %@,    Source Object: %@        Error: %@", self.managedObjectContext, sourceObject, (*error).description);
    NSAssert(self.managedObjectContext, @"Unable to perform mapping: No `managedObjectContext` assigned. (Mapping response.URL = %@)", self.response.URL);
....

我注意到上述方法称为27(此数字有所不同)之前,应用崩溃了。在每种情况下,都存在NSManagedObjectContext,即以下行:

I noticed that the above method was called 27 (this number varies) times prior to the app crashing. In each instance, NSManagedObjectContext was present i.e. the line below:

2014-12-07 18:44:48.721 MyApp[19011:3258405] managedObjectContext:managedObjectContext: <NSManagedObjectContext: 0x1701f5800>,    Source Object: {
    friends =     (
    );
}        Error: (null)

但是在崩溃之前,NSManagedObjectContext为空:

However right before it crashed, the NSManagedObjectContext was null:

2014-12-07 18:44:53.454 MyApp[19011:3258404] managedObjectContext: (null),    Source Object: {
    friends =     (
    );
}        Error: (null)

由于该应用正常运行了一段时间才崩溃,我不确定该如何解决。任何指针将不胜感激。

Since the app functions normally for a while before it crashes, I'm not sure how to address this. Any pointers would be greatly appreciated.

*编辑*

在Appdelegaate中。用户登录后,将在viewDidLoad中一次调用此方法。

In Appdelegaate. This method is called once in viewDidLoad when the User logs in.

- (RKManagedObjectStore *)managedObjectStore
{
    if (!_managedObjectStore && [Persistence loggedIn])
    {
        NSError * error;
        NSURL * modelURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"App" ofType:@"momd"]];
        NSManagedObjectModel * managedObjectModel = [[[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL] mutableCopy];
        self.managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];

        [_managedObjectStore createPersistentStoreCoordinator];

        NSArray * searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString * documentPath = [searchPaths objectAtIndex:0];

        NSString *dbName = [NSString stringWithFormat:@"%@App%@.sqlite", documentPath, [Persistence username]];
        NSPersistentStore * persistentStore = [_managedObjectStore addSQLitePersistentStoreAtPath:dbName
                                                                           fromSeedDatabaseAtPath:nil
                                                                                withConfiguration:nil
                                                                                          options:[self optionsForSqliteStore]
                                                                                            error:&error];
        NSAssert(persistentStore, @"Failed to add persistent store with error: %@", error);

        NSLog(@"Path: %@", dbName);

        if(!persistentStore)
        {
            NSLog(@"Failed to add persistent store: %@", error);
        }

        [_managedObjectStore createManagedObjectContexts];
        self.managedObjectStore.managedObjectCache = [[RKInMemoryManagedObjectCache alloc] initWithManagedObjectContext:self.managedObjectStore.persistentStoreManagedObjectContext];

        return self.managedObjectStore;
    }

    return _managedObjectStore;
}

- (id)optionsForSqliteStore
{
    return @{
             NSInferMappingModelAutomaticallyOption: @YES,
             NSMigratePersistentStoresAutomaticallyOption: @YES
             };
}

创建MOC:
对于核心数据栈,我正在使用在Xcode中创建项目时提供的AppDelegate中的默认核心数据代码。

Creating MOC: For Core Data stack, I'm using the Default Core Data code in AppDelegate that's provided when the project is created in Xcode.

- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

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

MOC操作:

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
             // Replace this implementation with code to handle the error appropriately.
             // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } 
    }
}

在应用程序内部,方法以下用于设置,获取和清除ObjectManager:

Inside the App, the methods below are used to set, get, and clear ObjectManager:

- (void)refreshMOC
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    self.objectManager = [self getObjectManager];

    self.objectManager.managedObjectStore = appDelegate.managedObjectStore;
    self.objectManager.managedObjectStore.managedObjectCache = appDelegate.managedObjectStore.managedObjectCache;
    self.managedObjectContext = self.objectManager.managedObjectStore.mainQueueManagedObjectContext;
}

- (RKObjectManager *)setupObjectManager
{
    NSURL *baseURL = [NSURL URLWithString:kBaseURL];
    AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:baseURL];
    RKObjectManager *manager = [[RKObjectManager alloc]initWithHTTPClient:httpClient];
    [manager.HTTPClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
    [manager setAcceptHeaderWithMIMEType:RKMIMETypeJSON];
    [manager.HTTPClient setParameterEncoding:AFJSONParameterEncoding];
    [RKMIMETypeSerialization registeredMIMETypes];
    [RKObjectManager setSharedManager:manager];

    return [RKObjectManager sharedManager];
}

- (RKObjectManager *)getObjectManager
{
    self.objectManager = (!self.objectManager) ?  [self setupObjectManager] : self.objectManager;
    return self.objectManager;
}

- (RKObjectManager*)newObjectManager
{
    [self clearRKObjectManager];
    return [self getObjectManager];
}

- (void)clearRKObjectManager
{
    if (self.objectManager)
    {
        self.objectManager = nil;
    }
}


推荐答案

删除所有应用程序委托模板的Core Data方法。当您使用RestKit并创建一个托管对象存储时,您是在要求RestKit为您管理Core Data堆栈,因此不需要其他方法(并且会造成混乱)。

Remove all of the app delegate template Core Data methods. When you use RestKit and create a managed object store you're asking RestKit to manage the Core Data stack for you so those other methods are not required (and confuse things).

当您需要MOC时,从托管对象存储中获取它。

When you need a MOC, get it / one from the managed object store.

注意,以上内容也适用于保存,因为您需要使用RestKit方法进行保存。而不是仅保存单个MOC。

Note, the above applies to saving too as you need to use the RestKit method for saving to the persistent store rather than just saving the individual MOC.

这篇关于RestKit:“ NSInternalInconsistencyException”,原因:“无法执行映射:未分配“ managedObjectContext”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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