0

我正在使用 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);
}];
}
4

2 回答 2

0

尝试以下操作:

NSManagedObjectContext *context = object.managedObjectContext;

[context deleteObject:object];

NSError *error;
if (![context save:&error]) {

NSLog(@"delete error");

// Handle the error, update UI etc.

}
于 2013-01-12T13:14:01.903 回答
0

我首先遵循亚历山大的回答的建议,但它只是从当前上下文中删除对象。重新启动应用程序后,将再次从核心数据中获取对象。

因此,您应该将更改保存到持久存储:

NSManagedObjectContext *context = objectToBeDeleted.managedObjectContext;
[context deleteObject:objectToBeDeleted];
NSError *error;
if (![context saveToPersistentStore:&error]) {
    NSLog(@"delete error %@", [error localizedDescription]);
}
于 2014-05-06T11:03:57.433 回答