我正在使用RestKit 0.2从我的服务器获取JSON文件并将对象映射到我的CoreData堆栈(类似于TwitterCoreData示例)。
在第一个请求中,我得到以下结果:Artist1, Artist2, Artist3
。
在第二个请求中,一位艺术家已过时,结果如下:Artist1, Artist3
。
现在应该从我的本地商店删除Artist2
并在我的UITableView
中消失。但是,我找不到从本地存储中删除Artist2
的方法。
如何从托管对象库中删除RestKit 0.2中的对象?
这就是我在做的事情:
#pragma mark - Data methods
- (void)fetchResults {
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Artists"];
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"ordernr" ascending:YES];
fetchRequest.sortDescriptors = @[descriptor];
NSError *error = nil;
// Setup fetched results
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:[RKManagedObjectStore defaultStore].mainQueueManagedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
[self.fetchedResultsController setDelegate:self];
BOOL fetchSuccessful = [self.fetchedResultsController performFetch:&error];
if(fetchSuccessful){
data = [self.fetchedResultsController fetchedObjects];
[_tableView reloadData];
NSLog(@"Fetched artists: %i", [[self.fetchedResultsController fetchedObjects] count]);
}
}
- (void)loadData {
[[RKObjectManager sharedManager] getObjectsAtPath:@"/artists.php" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(@"Fetched artists: %i", [[mappingResult array] count]);
for (id object in data) {
if (NO == [[mappingResult array] containsObject:object]){
NSLog(@"DELETE 1 object...");
//HOW TO DELETE THE OBJECT HERE??
}
}
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"ArtistsLastUpdatedAt"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self fetchResults];
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
RKLogError(@"Load failed with error: %@", error);
}];
}
答案 0 :(得分:0)
尝试以下方法:
NSManagedObjectContext *context = object.managedObjectContext;
[context deleteObject:object];
NSError *error;
if (![context save:&error]) {
NSLog(@"delete error");
// Handle the error, update UI etc.
}
答案 1 :(得分:0)
我首先按照亚历山大的回答提出建议,但它只是从当前的上下文中删除了对象。重新启动应用程序后,再次从核心数据中提取对象。
因此,您应该保存对持久存储的更改:
NSManagedObjectContext *context = objectToBeDeleted.managedObjectContext;
[context deleteObject:objectToBeDeleted];
NSError *error;
if (![context saveToPersistentStore:&error]) {
NSLog(@"delete error %@", [error localizedDescription]);
}