проблема хранения данных в таблицу sqlite с использованием основных данных - PullRequest
0 голосов
/ 25 июня 2011
    IfIDieAppDelegate.m

   - (void)createEditableCopyOfDatabaseIfNeeded

    { 

    // First, test for existence. 
    BOOL success; 

    NSFileManager *fileManager = [NSFileManager defaultManager]; 

    NSError *error; 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    //NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"DeathDiary.sqlite"];

    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"IfIDie.sqlite"];

    NSLog(@"%@",writableDBPath);

    success = [fileManager fileExistsAtPath:writableDBPath]; 

    if (success==YES)

    {

        NSLog(@"Database Already Exists");
        return;
    }
    else {

        NSLog(@"New Database Created");

        // The writable database does not exist, so copy the default to the appropriate location. 


    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"IfIDie.sqlite"]; 

        NSLog(@"Default : %@",defaultDBPath);

        success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; 

        if (!success) { 

            NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]); 

        } 

    }

}


- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (persistentStoreCoordinator != nil) {

        return persistentStoreCoordinator;

    }

    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"IfIDie.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;
}


NoteEditController.m


- (void)viewWillDisappear:(BOOL)animated{

    [super viewWillDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];

    if(saveChanges){

        // Save any changes to note
        if([[noteTextView text] length] > 0){

            if(noteToEdit){

                // Edit Note
                if([[titleField text] length] <= 0)

                    [noteToEdit setNoteTitle:[noteTextView text]];

                else

                    [noteToEdit setNoteTitle:[titleField text]];

                [noteToEdit setNoteText:[noteTextView text]];

            } else {
                // New Note
                Note *newNote = [NSEntityDescription 
insertNewObjectForEntityForName:@"Note" inManagedObjectContext:context];

                if([[titleField text] length] <= 0)

                    [newNote setNoteTitle:[noteTextView text]];

                else

                    [newNote setNoteTitle:[titleField text]];


                [newNote setNoteText:[noteTextView text]];

                NSLog(@"data saved");


            }

        } else {
            // Remove note (zero length)

            if(noteToEdit){

                [context deleteObject:noteToEdit];
            }
        }
    }
}

Здесь все идет хорошо, но данные не сохраняются в таблицу. Что может быть не так? Есть ли что-то с перезагрузкой базы данных? если, то я не понимаю, как решить. ошибки нет. Показывает журнал данных, сохраненных, но не сохраненных в таблице.

1 Ответ

0 голосов
/ 25 июня 2011

Вам нужно будет сохранить контекст , чтобы фактически зафиксировать ваши изменения в конце viewWillDisappear: method

NSError *error = nil; 
if (![context save: &error]) {
    // Couldn't save
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...