2014-09-11 5 views
0

Я использую основные данные, и у меня есть проблема. Когда я сохраняю данные и приложение все еще работает, я могу видеть и получать данные, которые были сохранены.Данные ядра Ios не сохранены

Как только приложение закрыто, все поля удалены и только объект сохраняется. Я вижу это в методе 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); 
    } 
} 

Это приложение делегируют функции:

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

ответ

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 
+0

Перед тем как приложение прекратить, в applicationWillTerminate Я вызываю метод saveContext. Это currect? или мне нужно каждый раз, когда я вставляю данные для вызова этой функции? –

+0

'applicationWillTerminate' не гарантируется. Не следует полагаться на сохранение вашего 'NSManagedObjectContext'. Контекст должен быть сохранен после вставки данных или в следующую логическую точку приложения. – dbart

+0

Эй, извините, но почему-то это не помогает. Код, который им используется для получения информации, в порядке? –

Смежные вопросы