更改核心堆栈后核心数据无法正常保存

时间:2016-02-03 18:50:06

标签: ios objective-c core-data save nsmanagedobjectcontext

我将现有的核心堆栈更改为此处推荐的核心堆栈:https://medium.com/soundwave-stories/core-data-cffe22efe716#.phv9wt6kd 而且储蓄不再有用了。我打开它时我的sqlite文件是空的,但是当我尝试访问存储在其中的数据时,它返回了数据错误的对象。我的实施错了吗?我需要做些什么才能让它发挥作用?

//头文件

@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (readonly, strong, nonatomic) NSManagedObjectContext *masterManagedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectContext *mainManagedObjectContext;

-(NSPersistentStoreCoordinator *)persistentStoreCoordinator;
-(NSManagedObjectModel *)managedObjectModel;
-(NSManagedObjectContext *)masterManagedObjectContext;
-(NSManagedObjectContext *)mainManagedObjectContext;
-(NSManagedObjectContext *)workerManagedObjectContext;

//实施文件

@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
@synthesize masterManagedObjectContext = __masterManagedObjectContext;
@synthesize mainManagedObjectContext = __mainManagedObjectContext;



//Managed object context
-(NSManagedObjectContext *)masterManagedObjectContext{
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        __masterManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
        [__masterManagedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return __masterManagedObjectContext;
}

- (NSManagedObjectContext *)mainManagedObjectContext {
    if (__mainManagedObjectContext != nil) {
        return __mainManagedObjectContext;
    }

    __mainManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [__mainManagedObjectContext setParentContext:self.masterManagedObjectContext];
    return __mainManagedObjectContext;
}

- (NSManagedObjectContext *)workerManagedObjectContext {

    NSManagedObjectContext *tempMOContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    tempMOContext.parentContext = [self mainManagedObjectContext];
    return tempMOContext;
}

//Save methods

- (void)saveWorkerContext:(NSManagedObjectContext *)context {
    NSError *error;
    [context save:&error];
    if (!error) {
    [self saveMainContext];
    }
}

- (void)saveMainContext {
    [self.mainManagedObjectContext performBlock:^{
        NSError *error = nil;
        [self.mainManagedObjectContext save:&error];
        if(!error){
            //Write to disk after saving on the main UI context
            [self saveMasterContext];
        }
    }];
}

- (void)saveMasterContext {

    [self.masterManagedObjectContext performBlock:^{
        NSError *error = nil;
        [self.masterManagedObjectContext save:&error];
        if(error){
            NSLog(@"CORE DATA MASTER CONTEXT ERROR : %@", error);
        }
    }];
}

-(NSManagedObjectModel *)managedObjectModel {
    if (__managedObjectModel != nil) {
        return __managedObjectModel;
    }

    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"MyResource"
                                                       ofType:@"bundle"];

    NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
    NSString *modelPath = [bundle pathForResource:@"MyData"
                                       ofType:@"momd"];
    //NSLog(@"Bundle modelURL:%@",modelPath);
    NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
    __managedObjectModel = [[NSManagedObjectModel alloc]     initWithContentsOfURL:modelURL];
    return __managedObjectModel;
}


-(NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    if (__persistentStoreCoordinator != nil) {
        return __persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"MyData.sqlite"];
    //NSLog(@"storeURL:%@",storeURL);
    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;
}

- (NSURL *)applicationDocumentsDirectory {
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

//尝试保存数据的示例

-(void)saveDictionary:(NSMutableDictionary *)myDictionary{

    NSManagedObjectContext *context = [self workerManagedObjectContext];
    [context performBlockAndWait:^{

        NSMutableDictionary *tmpDic = myDictionary;
        NSError *error;
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity"
                                              inManagedObjectContext:context];

        [fetchRequest setEntity:entity];
        NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];

        Entity *myEntity;

        if ([fetchedObjects count]>0) {
            myEntity = [fetchedObjects lastObject];
        }
        else{
            myEntity = [NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:context];
        }

        myEntity.value = tmpDic[@"value1"]!=nil?tmpDic[@"value1"]:@"nothing";


        [self saveWorkerContext:context];
    }];
}

0 个答案:

没有答案