0

I'am getting

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

and

while loading data from core data.I have referred links iOS Persistent store issue but it didnt solved my issue. Also data not saving to tableview. Earlier it was loading but due to large data I've used background core data saving. but for now No data loading from DB. I'm using NSFetchResultController for fetching data.

     -(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;

}

getting

  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)

When scrolling to last cell, I'm getting this crash too with nothing in the cell.

Community
  • 1
  • 1
Jan
  • 1,744
  • 3
  • 23
  • 38
  • If you wrap your import into a context performBlock does that help? – Daniel Galasko Apr 08 '15 at 12:05
  • Furthermore, are you aware that saving a context does not propagate to the persistent store, it only saves one level up:) – Daniel Galasko Apr 08 '15 at 12:05
  • Actually I'm not that much aware. My problem was while saving data into core data app became slow. So I did search stack over flow and found solution that need to use multithreading. You can see the code parent-child context. – Jan Apr 08 '15 at 12:11
  • @Muhsina Muhammed: Please try addidng an exception breakpoint. And let us know whic line is causing the exception. Do ou know how to do it? – Mayur Deshmukh Apr 08 '15 at 12:22
  • Yes but you have set the concurrency type of the context so it has now been allocated onto another thread. Remove your dispatch block and instead move all your code into the background context's performBlock method – Daniel Galasko Apr 08 '15 at 12:24
  • heres a semi decent post i glossed over http://stackoverflow.com/questions/24657437/core-data-background-context-best-practice – Daniel Galasko Apr 08 '15 at 12:25
  • @MayurDeshmukh yes i know, i will add and let you know, – Jan Apr 08 '15 at 12:25
  • @MayurDeshmukh Now app is stuck again for 20-30 seconds, background savings not affectively working. – Jan Apr 08 '15 at 12:44
  • When application gets stuck, pause your application from xcode and check what line is it stuck – Mayur Deshmukh Apr 08 '15 at 12:46
  • @MayurDeshmukh I have updated question, getting two types of crash now. – Jan Apr 08 '15 at 13:10

1 Answers1

0

Make sure you save your contexts in performBlock method like

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

Also refer this thread

Community
  • 1
  • 1
Mayur Deshmukh
  • 1,169
  • 10
  • 25
  • yes i did. but still no data fetching and updating tableview from coredata. – Jan Apr 08 '15 at 13:44
  • 1
    Some times data loads after that getting this error: CoreData: error: NULL _cd_rawData but the object is not being turned into a fault – Jan Apr 08 '15 at 14:22