Swift 核心数据:如何获取数组中的所有项目?

Swift Core Data: How to fetch all items in array?

我想删除我的 NSManagedObjects Weather 和 Currently 的现有内容。

let entityNames = ["Weather", "Currently"]
for entityName in entityNames {
    let fetchRequest = NSFetchRequest(entityName: entityName)
    let objects = try(context.execute(fetchRequest)) as? [NSManagedObject]
    for object in objects! {
        context.deletedObjects(object)
    }
}

但是使用此代码时,我在第 3 行收到一条错误消息:

Generic parameter 'ResultType' could not be inferred

您必须指定提取请求的通用类型

let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName)

那你甚至可以省略结果类型

let objects = try? context.execute(fetchRequest)

还有一个错字。你可能是说

context.deleteObject(object)

在 macOS 10.11+/ iOS 9.0+ 中,我们鼓励您使用 NSBatchDeleteRequest