核心数据:错误:在核心数据更改处理期间捕获到异常

时间:2014-09-12 15:57:04

标签: ios objective-c csv core-data

我现在已经有这个问题了几天而且真的很令人沮丧。我一直在审查我的代码一遍又一遍尝试不同的东西并且一直有同样的问题..这只发生了50%时代并非总是如此。这使得它更难..

问题,

我正在将3个csv文件中的数据解析为我的Core Data,其中2个文件解析总是顺利但中间/第二个文件是崩溃总是发生的地方,这将是该文件和managedObjectContext类的地址这个文件。

错误消息

CoreData: error: Serious application error.  
Exception was caught during Core Data change processing.  This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification.  
-[__NSCFSet addObject:]: attempt to insert nil with userInfo (null)
2014-09-12 11:27:06.115 AppName[210:3907] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFSet addObject:]: attempt to insert nil'

因此,在我的 FetchData 类中,我尝试以不同的方式解决问题。

  • 首先,我更改了我的.csv文件并将N / A插入到所有空白的字段/单元格中。
  • 其次,我在 FetchData 类中进行检查,如果它没有任何值,请保存N / A.
  • 第三,在我的视图控制器中,我解雇了数据,我现在已经在我的核心数据中为这3个实体分隔了三个不同的属性。
  

@property(非原子,强)NSManagedObjectContext * managedObjectContext;

     

@property(非原子,强)NSManagedObjectContext * managedObjectContextGI;

     

@property(非原子,强)NSManagedObjectContext * managedObjectContextVA;

这可能有点疯狂或其他什么,但我真的需要解决这个问题,尝试任何可能的解决方案或方法,我认为它始终是好的。

ViewController调用函数来执行解析..

//at the beginning of my model
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

-(IBAction)myLoadingTask:(id)sender{

       dispatch_async(kBgQueue, ^{

           NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

           NSString *savedValue = @"";

           if([[userDefaults stringForKey:@"dataFetched"] length] > 0){                            
               savedValue = [userDefaults stringForKey:@"dataFetched"];
           }

           // if the csv files data hasn't been fetch it, then fetch it
           if([savedValue length] == 0){

               FetchData *fd = [[FetchData alloc] initWithManagedContext:self.managedObjectContext];

               // fetching benefits data
               [fd beginParser];

               FetchGIBillData *fdGI = [[FetchGIBillData alloc] initWithManagedContext:self.managedObjectContextGI];

               // fetching gi bill data
               [fdGI beginParser];

               FetchVAPhones *fdVA = [[FetchVAPhones alloc] initWithManagedContext:self.managedObjectContextVA];

               // fetching va phones
               [fdVA beginParser];

               NSString *valueToSave = @"saved";
               [[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"dataFetched"];
               [[NSUserDefaults standardUserDefaults] synchronize];

           }

       });
}

这是我的核心数据模型功能等等。我已经执行了检查是否为空,保存 N / A 等等..所有我的我实体中的属性是字符串

#define GIBILL_FILENAME @"gi_bill_data"

int numOfEntries;
- (id)initWithManagedContext:(NSManagedObjectContext*)managedObjectContext
{
    self.managedObjectContext = managedObjectContext;
    arrayOfRecords = [[NSMutableArray alloc] init];
    numOfEntries=0;
    return self;
}


- (void) beginParser
{
    if (self.managedObjectContext == nil){
        // Error: Must pass in NSManagedObjectContext
        return;
    }

    NSString *filePath = [[NSBundle mainBundle] pathForResource:GIBILL_FILENAME ofType:@"csv"];
    NSInputStream *stream = [NSInputStream inputStreamWithFileAtPath:filePath];
    NSStringEncoding encoding = NSUTF8StringEncoding;//NSWindowsCP1250StringEncoding;

    CHCSVParser *parser = [[CHCSVParser alloc] initWithInputStream:stream usedEncoding:&encoding delimiter:','];
    parser.delegate = self;

    [parser parse];

    // uncomment to update data x amount of dates
    //[self checkDateForRefreshCSV:parser];

}

**这就是节约发生的地方! *

#pragma mark - Data Add
/**
 * addRows
 * @param parser: the CHCSV parser that will parse if required refresh
 * @brief: add the row to ths managedObjectContent DB. All values saved.
 */
- (void) addRows:(CHCSVParser *)parser
{
    int i = -1;
    if ([arrayOfRecords count] == 0) return;
    GIBill *data = [NSEntityDescription
                      insertNewObjectForEntityForName:@"GIBill"
                      inManagedObjectContext:self.managedObjectContext];

    if([[arrayOfRecords objectAtIndex:++i] length] > 2)
        data.facility_code = [arrayOfRecords objectAtIndex:i];
    else
        data.facility_code = @"N/A";

    if([[arrayOfRecords objectAtIndex:++i] length] > 2)
        data.institution = [arrayOfRecords objectAtIndex:i];
    else
        data.institution = @"N/A";

    if([[arrayOfRecords objectAtIndex:++i] length] > 2)
        data.city = [arrayOfRecords objectAtIndex:i];
    else
        data.city = @"N/A";

    if([[arrayOfRecords objectAtIndex:++i] length] > 2)
        data.state = [arrayOfRecords objectAtIndex:i];
    else
        data.state = @"N/A";

    if([[arrayOfRecords objectAtIndex:++i] length] > 2)
        data.country = [arrayOfRecords objectAtIndex:i];
    else
        data.country = @"N/A";

    if([[arrayOfRecords objectAtIndex:++i] length] > 2)
        data.bah = [arrayOfRecords objectAtIndex:i];
    else
        data.bah = @"N/A";

    if([[arrayOfRecords objectAtIndex:++i] length] > 2)
        data.poe = [arrayOfRecords objectAtIndex:i];
    else
        data.poe = @"N/A";

    if([[arrayOfRecords objectAtIndex:++i] length] > 2)
        data.yr = [arrayOfRecords objectAtIndex:i];
    else
        data.yr = @"N/A";

    if([[arrayOfRecords objectAtIndex:++i] length] > 2)
        data.gibill = [arrayOfRecords objectAtIndex:i];
    else
        data.gibill = @"N/A";

    if([[arrayOfRecords objectAtIndex:++i] length] > 0)
        data.cross = [arrayOfRecords objectAtIndex:i];
    else
        data.cross = @"N/A";

    if([[arrayOfRecords objectAtIndex:++i] length] > 2)
        data.grad_rate = [arrayOfRecords objectAtIndex:i];
    else
        data.grad_rate = @"N/A";

    if([[arrayOfRecords objectAtIndex:++i] length] > 2)
        data.grad_rate_rank = [arrayOfRecords objectAtIndex:i];
    else
        data.grad_rate_rank = @"N/A";

    if([[arrayOfRecords objectAtIndex:++i] length] > 2)
        data.default_rate = [arrayOfRecords objectAtIndex:i];
    else
        data.default_rate = @"N/A";

    if([[arrayOfRecords objectAtIndex:++i] length] > 2)
        data.avg_stu_loan_debt = [arrayOfRecords objectAtIndex:i];
    else
        data.avg_stu_loan_debt = @"N/A";

    if([[arrayOfRecords objectAtIndex:++i] length] > 2)
        data.avg_stu_loan_debt_rank = [arrayOfRecords objectAtIndex:i];
    else
        data.avg_stu_loan_debt_rank = @"N/A";

    if([[arrayOfRecords objectAtIndex:++i] length] > 2)
        data.indicator_group = [arrayOfRecords objectAtIndex:i];
    else
        data.indicator_group = @"N/A";

    if([[arrayOfRecords objectAtIndex:++i] length] > 2)
        data.salary = [arrayOfRecords objectAtIndex:i];
    else
        data.salary = @"N/A";

    if([[arrayOfRecords objectAtIndex:++i] length] > 2)
        data.zip = [arrayOfRecords objectAtIndex:i];
    else
        data.zip = @"N/A";

    if([[arrayOfRecords objectAtIndex:++i] length] > 2)
        data.ope = [arrayOfRecords objectAtIndex:i];
    else
        data.ope = @"N/A";

    NSError *error;

    [self.managedObjectContext save:&error];

}

好吧,我发布了最相关的代码,我想到了这个问题。如果需要其他东西或有关问题的更多细节,请告诉我,我会提供..

提前致谢!

4 个答案:

答案 0 :(得分:27)

下面的一行节省了我的一天:

_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];

您只需将并发类型设置为Private。这样它就可以在私有队列上同时对数据库执行多个操作。

答案 1 :(得分:23)

好吧,整个问题是创建NSManagedObjectContext以及Main Thread中的所有内容,然后访问它或在Background Thread中使用它。

所以,我刚刚关注this post,现在一切都运转得很顺利:)

非常感谢这些评论,它确实让我朝着正确的方向前进,这完全是我需要能够找到问题的。

谢谢!

在AppDelegate.h

+ (NSManagedObjectContext *)mainQueueContext;
+ (NSManagedObjectContext *)privateQueueContext;

然后,在我的AppDelegate.m

#pragma mark - Singleton Access

+ (NSManagedObjectContext *)mainQueueContext
{
    return [self mainQueueContext];
}

+ (NSManagedObjectContext *)privateQueueContext
{
    return [self privateQueueContext];
}

#pragma mark - Getters

- (NSManagedObjectContext *)mainQueueContext
{
    if (!_mainQueueContext) {
        _mainQueueContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
        _mainQueueContext.persistentStoreCoordinator = self.persistentStoreCoordinator;
    }

    return _mainQueueContext;
}

- (NSManagedObjectContext *)privateQueueContext
{
    if (!_privateQueueContext) {
        _privateQueueContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
        _privateQueueContext.persistentStoreCoordinator = self.persistentStoreCoordinator;
    }

    return _privateQueueContext;
}

- (id)init
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(contextDidSavePrivateQueueContext:)
                                                     name:NSManagedObjectContextDidSaveNotification
                                                   object:[self privateQueueContext]];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(contextDidSaveMainQueueContext:)
                                                     name:NSManagedObjectContextDidSaveNotification
                                                   object:[self mainQueueContext]];
    }
    return self;
}

#pragma mark - Notifications

- (void)contextDidSavePrivateQueueContext:(NSNotification *)notification
{
    @synchronized(self) {
        [self.mainQueueContext performBlock:^{
            [self.mainQueueContext mergeChangesFromContextDidSaveNotification:notification];
        }];
    }
}

- (void)contextDidSaveMainQueueContext:(NSNotification *)notification
{
    @synchronized(self) {
        [self.privateQueueContext performBlock:^{
            [self.privateQueueContext mergeChangesFromContextDidSaveNotification:notification];
        }];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

最后,在我的 ViewController 中,我将工作发送到后台..

// dont forget the macro
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

dispatch_async(kBgQueue, ^{

    id delegate = [[UIApplication sharedApplication] delegate];
    self.managedObjectContext = [delegate privateQueueContext];

    // do something in the background with your managedObjectContext!!!!

 });

答案 2 :(得分:0)

对于在Swift 3中执行此操作的人:

var managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)

答案 3 :(得分:-1)

在Swift 4中,我使用以下模板:

// MARK: - Core Data stack

lazy var persistentContainer: NSPersistentContainer = {
    /*
     The persistent container for the application. This implementation
     creates and returns a container, having loaded the store for the
     application to it. This property is optional since there are legitimate
     error conditions that could cause the creation of the store to fail.
     */
    let container = NSPersistentContainer(name: "Model")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() 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.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

lazy var viewContext: NSManagedObjectContext = {
    return self.persistentContainer.viewContext
}()

lazy var cacheContext: NSManagedObjectContext = {
    return self.persistentContainer.newBackgroundContext()
}()

lazy var updateContext: NSManagedObjectContext = {
    let _updateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
    _updateContext.parent = self.viewContext
    return _updateContext
}()

和updateContext用于更新操作。