我有一个查询核心数据实体“MyGalleryPhoto”的 NSFetchedResultsController。
我正在尝试删除一些对象,并遇到一些问题。我正在使用 MagicalRecord。这是我对代码的最初尝试,在我看来应该可以正常工作。在代码运行时,对象肯定存在,因为它们显示在 fetchedResultsController 中。
[MagicalRecord saveInBackgroundWithBlock:^(NSManagedObjectContext *localContext) {
for (MyGalleryPhoto *myGalleryPhoto in [self.fetchedResultsController.fetchedObjects objectsAtIndexes: self.selectedIndexes]) {
NSError *error = nil;
MyGalleryPhoto *localMyGalleryPhoto = (MyGalleryPhoto *) [localContext existingObjectWithID: myGalleryPhoto.objectID error: &error];
NSLog(@"error: %@:%@", [error localizedDescription], [error userInfo]);
NSLog(@"mygp: %@", [localMyGalleryPhoto description]);
[localMyGalleryPhoto deleteInContext: localContext];
}
} completion:^(void){
}];
此代码不起作用。找不到 myGalleryPhoto 条目,返回的错误是:“操作无法完成。(Cocoa 错误 133000。)”我也尝试使用 MR_inContext,它只调用 existingObjectWithId:error:。
经过一番折腾,我想出了这个邪恶的科学怪人的怪物,它从实体中获取所有记录并比较 ObjectID 的字符串表示形式。这工作正常。为什么?我正在使用我今天从 GitHub 下载的 MagicalRecord 副本、最新的 XCode、最新的 SDK 等等。
[MagicalRecord saveInBackgroundWithBlock:^(NSManagedObjectContext *localContext) {
NSArray *allMyGalleryPhotos = [MyGalleryPhoto findAllInContext: localContext];
for (MyGalleryPhoto *myGalleryPhoto in [self.fetchedResultsController.fetchedObjects objectsAtIndexes: self.selectedIndexes]) {
MyGalleryPhoto *myGalleryPhotoToDelete = nil;
for (MyGalleryPhoto *existingMyGalleryPhoto in allMyGalleryPhotos) {
NSString *existingURLString = [[existingMyGalleryPhoto.objectID URIRepresentation] absoluteString];
NSString *URLString = [[myGalleryPhoto.objectID URIRepresentation] absoluteString];
NSLog(@"ExistingURLString: %@", existingURLString);
NSLog(@"URLString: %@", URLString);
if ([URLString isEqualToString: existingURLString]) {
myGalleryPhotoToDelete = existingMyGalleryPhoto;
}
}
if (myGalleryPhotoToDelete) [myGalleryPhotoToDelete deleteInContext: localContext];
}
} completion:^(void){
}];