Я новичок в Core Data и, как таковой, не уверен, допустил ли я ошибку. Я загрузил некоторые данные из REST API и успешно сохраняет ответ JSON
на диск. Я пытаюсь обрабатывать данные и сохранять их настойчиво с помощью Core Data.Основные данные не сохраняют объекты настойчиво
NSLog(@"inserted objects: %@", [managedObjectContext insertedObjects]);
[managedObjectContext performBlockAndWait:^{
NSError *error = nil;
if (![managedObjectContext save:&error]) {
NSLog(@"Unable to save context for class %@", className);
} else {
NSLog(@"saved all records!");
}
}];
Я успешно обработал JSON
и добавить его к NSManagedObjectContext
. В первой строке это показывает, что я успешно попытался вставить 2 объекта.
inserted objects: {(
<User: 0xa259af0> (entity: User; id: 0xa259b70 <x-coredata:///User/t44BB97D0-C4B4-4BA6-BD25-13CEFDAE665F3> ; data: {
email = "[email protected]";
experience = "2013-07-20";
"first_name" = Vishnu;
id = 2;
"job_title" = Developer;
"last_name" = Prem;
location = "";
"phone_number" = "+6590091516";
"profile_pic" = "";
"thumbnail_profile_pic" = "";
"user_id" = 2;
}),
<User: 0xa25e460> (entity: User; id: 0xa25e4c0 <x-coredata:///User/t44BB97D0-C4B4-4BA6-BD25-13CEFDAE665F2> ; data: {
email = "[email protected]";
experience = "2013-07-20";
"first_name" = Sanchit;
id = 1;
"job_title" = Developer;
"last_name" = Bareja;
location = "";
"phone_number" = "+15106127328";
"profile_pic" = "";
"thumbnail_profile_pic" = "";
"user_id" = 1;
})
)}
Когда я попытался [managedObjectContext save:&error]
, он делает это успешно и распечатать «сохранены все записи», как и ожидалось. Однако, когда я перехожу к своему файлу .sqlite
и проверяю наличие добавленных объектов, я понимаю, что он не добавил никаких объектов в db.
При повторном подключении я распечатываю список объектов, которые уже находятся в базе данных, и подтверждает, что я еще не сохранил.
Кто-нибудь знает, что происходит, и почему я не могу сохранить данные настойчиво, хотя похоже, что я успешно создал объекты «Пользователь», которые необходимо сохранить в модели Core Data.
EDIT:
здесь, где я создаю NSPersistentStoreCoordinator
// 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:@"RTModel.sqlite"];
NSError *error = nil;
NSLog(@"Test 1");
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSLog(@"Test 2");
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&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.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
У меня есть 3 контексты.
masterManagedObjectContext
backgroundManagedObjectContext
newManagedObjectContext
мастер родитель как фон и новый. Когда я запрашиваю контексты, как это:
NSError *error = nil;
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"User"];
[request setSortDescriptors:[NSArray arrayWithObject:
[NSSortDescriptor sortDescriptorWithKey:@"id" ascending:YES]]];
[request setReturnsObjectsAsFaults:NO];
NSArray *testArray = [[[RTCoreDataController sharedInstance] newManagedObjectContext] executeFetchRequest:request error:&error];
for (User *obj in testArray) {
NSLog(@"obj.id %@", obj.id);
}
NSLog(@"query records: %@",testArray);
мастеров и фон возвращает правильный obj.id в NSLog, а также дает выход ниже @ «запись запроса»
(
"<User: 0xa3811d0> (entity: User; id: 0xa381230 <x-coredata:///User/t92BCED2D-CD17-49CC-9EBA-DF8F52F06A002> ; data: {\n email = \"[email protected]\";\n experience = \"2013-07-20\";\n \"first_name\" = Sanchit;\n id = 1;\n \"job_title\" = Developer;\n \"last_name\" = Bareja;\n location = \"\";\n \"phone_number\" = \"+15106127328\";\n \"profile_pic\" = \"\";\n \"thumbnail_profile_pic\" = \"\";\n \"user_id\" = 1;\n})",
"<User: 0xa382170> (entity: User; id: 0xa3820b0 <x-coredata:///User/t92BCED2D-CD17-49CC-9EBA-DF8F52F06A003> ; data: {\n email = \"[email protected]\";\n experience = \"2013-07-20\";\n \"first_name\" = Vishnu;\n id = 2;\n \"job_title\" = Developer;\n \"last_name\" = Prem;\n location = \"\";\n \"phone_number\" = \"+6590091516\";\n \"profile_pic\" = \"\";\n \"thumbnail_profile_pic\" = \"\";\n \"user_id\" = 2;\n})"
)
однако " новый»возвращает (null)
для obj.id в NSLog
и возвращает следующий за @"query records"
:
(
"<User: 0xa2b08a0> (entity: User; id: 0x95aebe0 <x-coredata:///User/tBFCC6C5F-7D2C-4AA0-BA96-B806EE360A762> ; data: <fault>)",
"<User: 0xa2b0910> (entity: User; id: 0xa4b9780 <x-coredata:///User/tBFCC6C5F-7D2C-4AA0-BA96-B806EE360A763> ; data: <fault>)"
)
Можете ли вы разместить свой код, где вы создаете свой 'NSPersistentStoreCoordinator' и' NSManagedObjectContext'? Если они неправильно сконфигурированы, это поможет увидеть их там. –
@JeffKelley сделал соответствующие изменения! Я прошел через учебник здесь (http://www.raywenderlich.com/15916/how-to-synchronize-core-data-with-a-web-service-part-1), и он работает, но когда я попытался настроить это для моего собственного REST API, он терпит неудачу. –
Вы получили «сохраненные записи!». после регистрации вставленных объектов? –