我很想知道什麼最好的方法是在RestKit 0.20中創建一個新的NSManagedObject?目前我的代碼看起來像這樣:RestKit 0.20 - 創建新的NSManagedObject的首選方法是什麼?
#pragma mark - navigation buttons
- (void)createButtonDidTouch
{
// create new album object
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
NSManagedObjectContext *parentContext = RKObjectManager.sharedManager.managedObjectStore.mainQueueManagedObjectContext;
context.parentContext = parentContext;
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Album" inManagedObjectContext:parentContext];
Album *newAlbum = [[Album alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:context];
// pass object to create view to manipulate
AlbumCreateViewController *createViewController = [[AlbumCreateViewController alloc] initWithData:newAlbum];
createViewController.delegate = self;
createViewController.managedObjectContext = context;
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:createViewController];
navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentViewController:navController animated:YES completion:nil];
}
#pragma mark - create view controller delegate
- (void)createViewControllerDidSave:(NSManagedObject *)data
{
// dismiss the create view controller and POST
// FIXME: add restkit code to save the object
NSLog(@"save the object...");
NSDictionary *userInfo = [KeychainUtility load:@"userInfo"];
NSString *path = [NSString stringWithFormat:@"/albums/add/%@/%@", userInfo[@"userID"], userInfo[@"apiKey"]];
[RKObjectManager.sharedManager postObject:data path:path parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
operation.targetObject = data;
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(@"create album error: %@", error);
}];
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)createViewControllerDidCancel:(NSManagedObject *)data
{
// dismiss the create view controller
NSLog(@"delete the object...");
// FIXME: add restkit code to delete the object
[self dismissViewControllerAnimated:YES completion:nil];
}
我也很想知道我的責任是保存/刪除此對象。如果我通過RestKit POST到服務器是否保存了託管對象上下文?
如果我決定取消創建過程 - 刪除此對象的首選方法是什麼?
基本上RestKit爲我做了多少事,我應該確保我在做什麼。我還沒有找到很多關於這方面的文件,希望能夠明確。
那麼我會如何刪除這個對象 - 假設我使用上面的代碼創建了對象,但沒有觸發POST請求 - 而是取消/關閉了「創建」視圖控制器?只通過我的本地NSMangedObjectContext? –
在上面的代碼中,它被插入到上下文中,但未保存。你可以從解除視圖控制器的上下文中刪除它。但是我建議你不要直接將對象插入到'managedObjectStore.mainQueueManagedObjectContext'中,而是在繼續創建控制器並將其分配給控制器時創建一個子託管對象上下文。你可以做的只是讓MOC在你取消時解除分配。 –
是否有創建子上下文的快捷方式?在我記得使用像[Album createObject]之類的東西之前 - 或者類似的東西。 –