gpt4 book ai didi

ios - 将 NSPersistentStoreResult 转换为数组

转载 作者:搜寻专家 更新时间:2023-10-30 22:05:26 25 4
gpt4 key购买 nike

您好,我在使用以下代码时遇到问题。具体来说,if let 语句给出了 Cast from NSPeristentStoreResult to unrelated type [Item] always fails 警告。我正在使用 Swift 3.01。

看起来这应该很容易做到。我关注的这本书是使用早期版本的 Swift 编写的。谢谢你的宽容。

func demo(){

let request = NSFetchRequest<Item>(entityName: "Item")

do {
if let items = try CDHelper.shared.context.execute(request) as? [Item] {
for item in items {
if let name = item.name {
print("Fetched Managed Object = '\(name)'")
}
}
}
} catch {
print("Error executing a fetch request: \(error)")
}
}

最佳答案

使用fetch()代替execute():

if let items = try CDHelper.shared.context.fetch(request)
...

或者在您的上下文中使用perform:

 CDHelper.shared.context.perform {
let fetchRequest: NSFetchRequest<Item> = Item.fetchRequest()
let items = try! fetchRequest.execute()
for item in items {
if let name = item.name {
print("Fetched Managed Object = '\(name)'")
}
}
}

关于ios - 将 NSPersistentStoreResult 转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40910773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com