从核心数据中删除二进制数据 iOS 8

deleting binary data from Core Data iOS 8

我有一个允许用户从网站下载图片的应用程序。 (玩具收藏家清单 2 - https://itunes.apple.com/us/app/toy-collector-checklist-2/id919363870?mt=8

用户理论上可以下载数千张图像,造成相当大的使用量。我正在尝试添加 "Delete All Images" 以便用户可以在不删除应用程序的情况下清除图像。

代码似乎有效。当按下按钮时图像不再可见,当我检查它时核心数据值 returns "nil" - 但是当我进入我的使用设置时 space 没有出现被释放。我正在使用我认为非常标准的获取和更新代码:

CoreDataHelper *cdh =
[(AppDelegate *)[[UIApplication sharedApplication] delegate] cdh];

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
                               entityForName:@"Item"
                               inManagedObjectContext:cdh.context];
[fetchRequest setEntity:entity];
//   [fetchRequest setPredicate:nil];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"photo != nil OR photoAlt != nil OR photoCam != nil"]];
[fetchRequest setFetchBatchSize:500];
NSManagedObject *removePhotoFromObject;
NSError *error = nil;
NSArray *results = [cdh.context executeFetchRequest:fetchRequest error:&error];
for (removePhotoFromObject in results) {
    [removePhotoFromObject setValue:nil forKey:@"photoCam"];
    [removePhotoFromObject setValue:nil forKey:@"photo"];
    [removePhotoFromObject setValue:nil forKey:@"photoAlt"];
    [removePhotoFromObject setValue:nil forKey:@"thumbnail"];



}
[cdh backgroundSaveContext];

这会将可能的照片位置的值设置为零。如果我再次 运行 相同的代码,它不会将它们添加到数组中(因为它们的值现在为 nil),所以我知道该部分正在工作。并且图像和缩略图被删除。但是当我在“设置”选项卡中查看时,数据使用情况并没有改变。

可能会破坏工作的东西:

项目是一个实体。 photo、photoAlt 和 photoCam 也是每个实体,与 Item

有 "To One" 关系

它们在模型中都被归因为 "Binary Data"。

如有任何想法和建议,我们将不胜感激。我已经查看了这些论坛以及更大的互联网,但到目前为止找不到解决方案。

扎克

虽然您将关系设置为 nil,但您并没有删除关联的对象。所以我怀疑它们仍在您的数据库中。请尝试改用以下内容:

NSArray *results = [cdh.context executeFetchRequest:fetchRequest error:&error];
for (removePhotoFromObject in results) {
    if (removePhotoFromObject.photoCam) [cdh.context deleteObject:removePhotoFromObject.photoCam];
    if (removePhotoFromObject.photo) [cdh.context deleteObject:removePhotoFromObject.photo];
    if (removePhotoFromObject.photoAlt) [cdh.context deleteObject:removePhotoFromObject.photoAlt];
    if (removePhotoFromObject.thumbnail) [cdh.context deleteObject:removePhotoFromObject.thumbnail];
}

这应该会从您的数据库中删除对象(当您保存上下文时),但请注意,这可能不会立即减少使用的存储空间。来自 CoreData Programming Guide:

Simply deleting a record from a SQLite store does not necessarily result in a reduction in the size of the file. If enough items are removed to free up a page in the database file, SQLite’s automatic database vacuuming will reduce the size of the file as it rearranges the data to remove that page. Similarly, the file size may be reduced if you remove an item that itself occupies multiple pages (such as a thumbnail image).