Ios核心数据未保存

时间:2014-09-11 15:07:36

标签: ios objective-c core-data

我使用核心数据,但我遇到了问题。当我保存数据并且应用程序仍在运行时,我可以看到并获取已保存的数据。

应用程序关闭后,将删除所有字段并保存对象。我可以在saveContext方法中看到它。 在应用程序关闭时首次启动时,将激活saveContext方法。我可以看到managedObjectContext对象正在插入新对象。 应用程序打开的下一次,managedObjectContext正在更新对象,所以我知道它保存对象但是当我尝试检索它可以找到的对象时。

这是我如何插入对象:

AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;

    self.managedObjectContext = appDelegate.managedObjectContext;

    @try {
        UserData *userData  =[NSEntityDescription insertNewObjectForEntityForName:[UserTable tableName]                                               inManagedObjectContext:self.managedObjectContext];

        //Insert Values
        userData.facebookId=user.id;
        userData.name=user.name;
        userData.picoAccessToken=[PicoApiManager sharedInstance].accessToken;
        userData.picoExpire=[PicoApiManager sharedInstance].expires;
        userData.latitude=[NSNumber numberWithDouble:user.latitude];
        userData.longitude=[NSNumber numberWithDouble:user.longitude];
        userData.pushId=user.pushId;
        userData.isActive=[NSNumber numberWithBool:activeStatus];
    }
    @catch (NSException *exception) {
        NSLog(@"Insert exception - %@", exception.description);
    }

  -(void)addPictures:(NSMutableArray *)Pictures;
 {
//Setting the isNew field to NO to all the pictures already in the db 
[self updateIsNewOfPicture];
for (Picture *picture in Pictures) {
//Checks if inserted picture is already inside the table

    AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;

    self.managedObjectContext = appDelegate.managedObjectContext;

    @try {
    PictureData *pictureData=[NSEntityDescription insertNewObjectForEntityForName:[PicturesTable     tableName]inManagedObjectContext:self.managedObjectContext];

    //Insert Values
    pictureData.url=picture.source;
    pictureData.isNew=[NSNumber numberWithBool:YES];
    pictureData.isPick=[NSNumber numberWithBool:NO];
    pictureData.timeTaken=picture.time_taken;
    pictureData.albumData=[self getActiveAlbum];
    }
    @catch (NSException *exception) {
        NSLog(@"Insert exception - %@", exception.description);
    }
}

这是app委托功能:

     - (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]);
        } 
    }
}

#pragma mark - Core Data stack

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_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:@"Pico-Db" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Pico.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;
}

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

这就是我试图获取数据的方式:

  AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
    //2
    // initializing NSFetchRequest
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    //Setting Entity to be Queried
    NSEntityDescription *entity = [NSEntityDescription entityForName:[UserTable tableName] inManagedObjectContext:appDelegate.managedObjectContext];


    [fetchRequest setEntity:entity];
    NSError* error;

    // Query on managedObjectContext With Generated fetchRequest
    NSArray *fetchedRecords = [appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedRecords.count >0) {
        return YES;
    }

    return NO;

1 个答案:

答案 0 :(得分:0)

在插入数据后,您必须调用-[AppDelegate saveContext],以便CoreData将更改保留到磁盘。 NSManagedObjectContext将存储内存中的更改,因此当您的应用程序仍处于活动状态时,您将可以访问数据。但是,只要应用终止,除非您致电-[AppDelegate saveContext],否则这些更改将不会保留。

在第一个例子中尝试这个:

AppDelegate *appDelegate  = [UIApplication sharedApplication].delegate;
self.managedObjectContext = appDelegate.managedObjectContext;

@try {
    UserData *userData = [NSEntityDescription insertNewObjectForEntityForName:[UserTable tableName] inManagedObjectContext:self.managedObjectContext];

    //Insert Values
    userData.facebookId=user.id;
    userData.name=user.name;
    userData.picoAccessToken=[PicoApiManager sharedInstance].accessToken;
    userData.picoExpire=[PicoApiManager sharedInstance].expires;
    userData.latitude=[NSNumber numberWithDouble:user.latitude];
    userData.longitude=[NSNumber numberWithDouble:user.longitude];
    userData.pushId=user.pushId;
    userData.isActive=[NSNumber numberWithBool:activeStatus];

} @catch (NSException *exception) {
    NSLog(@"Insert exception - %@", exception.description);
}

// SAVE CONTEXT:
[appDelegate saveContext];

在第二个例子中尝试这个:

for (Picture *picture in Pictures) {
    // Checks if inserted picture is already inside the table

    AppDelegate* appDelegate  = [UIApplication sharedApplication].delegate;
    self.managedObjectContext = appDelegate.managedObjectContext;

    @try {
        PictureData *pictureData = [NSEntityDescription insertNewObjectForEntityForName:[PicturesTable tableName]inManagedObjectContext:self.managedObjectContext];

        //Insert Values
        pictureData.url=picture.source;
        pictureData.isNew=[NSNumber numberWithBool:YES];
        pictureData.isPick=[NSNumber numberWithBool:NO];
        pictureData.timeTaken=picture.time_taken;
        pictureData.albumData=[self getActiveAlbum];

    } @catch (NSException *exception) {
        NSLog(@"Insert exception - %@", exception.description);
    }
}

// SAVE CONTEXT:
[appDelegate saveContext];

创建获取请求:

NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"YourEntityName"];
request.sortDescriptors = [NSSortDescriptor sortDescriptorWithKey:@"attributeName" ascending:YES];
request.predicate       = [NSPredicate predicateWithFormat:@"attribute == %@", 13];

NSError *error   = nil; // 
NSArray *results = [appDelegate.managedObjectContext executeFetchRequest:request error:&error];
if (!results) {
    NSLog(@"Error performing fetch request: %@", error.localizedDescription);
}

return ([results count] > 0); // There are more efficient ways of getting count from CoreData