通过iOS获取应用程序崩溃持久存储问题和未从Coredata加载的数据

时间:2015-04-08 11:44:33

标签: ios objective-c core-data

我正在

 Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSManagedObject persistentStore]: unrecognized selector sent to instance 0x3bebf50'  

从核心数据加载数据时。我已经引用了链接iOS Persistent store issue,但它没有解决我的问题。还有数据没有保存到tableview。 早些时候它是加载,但由于大数据我已经使用了后台核心数据保存。但是现在没有DB加载数据。我使用NSFetchResultController来获取数据。

     -(void)updateThreadEntityWithSyncDetails:(NSMutableDictionary *)inDictionary
{

  dispatch_queue_t backgroundQueue = dispatch_queue_create("backgroundQueueName", NULL);
NSString *loginUser=[[NSUserDefaults standardUserDefaults] valueForKey:@"currentUser"];

    AppDelegate *sharedDelegate = (AppDelegate *)[[UIApplication   sharedApplication] delegate];
    NSManagedObjectContext *context = [sharedDelegate managedObjectContext];

    NSManagedObjectContext *contextforThread = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];

    contextforThread.parentContext = context;

    [contextforThread performBlock:^{
    //    AppDelegate *sharedDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    //    NSManagedObjectContext *context = [sharedDelegate managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setReturnsObjectsAsFaults:NO];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"ThreadInfo"
                                              inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSPredicate *userPredicate = [NSPredicate predicateWithFormat:@"userEmail == %@",loginUser];
    NSPredicate *threadPredicate = [NSPredicate predicateWithFormat:@"threadID == %@",[inDictionary valueForKey:@"thread"]];
    NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates: @[userPredicate, threadPredicate]];
    [fetchRequest setPredicate:compoundPredicate];

    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:nil];
    for (ThreadInfo *threadInfo in fetchedObjects)
    {
        if([[inDictionary allKeys] containsObject:@"userEmail"])
        {
            if([inDictionary valueForKey:@"userEmail"]!=[NSNull null])
            {
                threadInfo.userEmail=[inDictionary valueForKey:@"userEmail"];
            }
        }
        if([[inDictionary allKeys] containsObject:@"secret_seed"])
        {
            if([inDictionary valueForKey:@"secret_seed"]!=[NSNull null])
            {
                threadInfo.threadSecret=[NSString stringWithFormat:@"%@",[inDictionary valueForKey:@"secret_seed"]];
            }
        }
        if([[inDictionary allKeys] containsObject:@"r_key"])
        {
            if([inDictionary valueForKey:@"r_key"]!=[NSNull null])
            {
                threadInfo.remoteKey=[inDictionary valueForKey:@"r_key"];
            }
        }
        if([[inDictionary allKeys] containsObject:@"solicitation"])
        {
            if([inDictionary valueForKey:@"solicitation"]!=[NSNull null])
            {
                threadInfo.solicitationID=[inDictionary valueForKey:@"solicitation"];
            }
        }
        if([[inDictionary allKeys] containsObject:@"r_secret"])
        {
            if([inDictionary valueForKey:@"r_secret"]!=[NSNull null])
            {
                threadInfo.remoteSecret=[inDictionary valueForKey:@"r_secret"];
            }
        }



    NSError *error;

    if (![contextforThread save:&error]) {
        NSLog(@"Could not insert to userInfo: %@", [error localizedDescription]);
    }
            [context performBlock:^{

        NSError *error;
        if (![context save:&error]) {
            NSLog(@"Could not insert to userInfo: %@", [error localizedDescription]);
        }

    }];


}];


//    if (![context save:&error]) {
//        NSLog(@"Could not update to threadInfo: %@", [error localizedDescription]);
//    }

}

的appDelegate

   - (void)saveContext
 {
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
    if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
                  NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();

  }
 }
 }

  #pragma mark - Core Data stack


- (NSManagedObjectContext *)managedObjectContext
 {


if (_managedObjectContext != nil) {
    return _managedObjectContext;
}


NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
    //        _managedObjectContext = [[NSManagedObjectContext alloc] init];
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];

    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;

 }

// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil) {
    return _managedObjectModel;
}

   NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"IXCoreDataModel" withExtension:@"momd"];
  _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
  return _managedObjectModel;
}


- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
  {

 if (_persistentStoreCoordinator != nil) {
    return _persistentStoreCoordinator;
}

NSURL *storeURL = [[self applicationDocumentsDirectory]   URLByAppendingPathComponent:@"Inxed.sqlite"];

 NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
    /*
     */
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

return _persistentStoreCoordinator;
}

 #pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
   - (NSURL *)applicationDocumentsDirectory
    {

   return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory   inDomains:NSUserDomainMask] lastObject];

  }

FetchedResultsController

  -(NSFetchedResultsController*)fetchedResultsController
{

if (_fetchedResultsController != nil) {
    return _fetchedResultsController;
}

NSString *loginUser=[[NSUserDefaults standardUserDefaults] valueForKey:@"currentUser"];

AppDelegate *sharedDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [sharedDelegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setReturnsObjectsAsFaults:NO];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"ThreadInfo"
                                          inManagedObjectContext:context];
[fetchRequest setEntity:entity];

NSSortDescriptor *sort = [[NSSortDescriptor alloc]
                          initWithKey:@"threadDate" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];


NSPredicate *threadPredicate = [NSPredicate predicateWithFormat:@"userEmail == %@",loginUser];
// NSPredicate *providerPredicate = [NSPredicate predicateWithFormat:@"isReceiver == YES"];
//  NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates: @[threadPredicate, providerPredicate]];
[fetchRequest setPredicate:threadPredicate];
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *theFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                    managedObjectContext:context sectionNameKeyPath:nil
                                               cacheName:nil];
_fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;

return _fetchedResultsController;

}

CRASH CODE

     - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
 {

  ThreadInfo *info=[_fetchedResultsController objectAtIndexPath:indexPath];


if([info.isSystemMessage boolValue])// CRASH CoreData: error: NULL _cd_rawData but the object is not being turned into a fault

    {

    return 178+90+25;


} else {


    return 178;

}

获得

  CoreData: error: Serious application error.  An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:.  Only run on the main thread! with userInfo (null)

当滚动到最后一个单元格时,我在单元格中没有任何内容也会发生此崩溃。

1 个答案:

答案 0 :(得分:1)

确保将您的上下文保存在performBlock方法中,如

[mainContext performBlock^{
    [mainContext save:&error];
}];

另请参阅this thread