我试图读取存储在核心数据数据库中的实体(称为“List”)的属性(称为“name”)的值。我遇到的问题是它说这个属性的值是nil,应该是一个字符串。
我检索所有列表实体的代码如下:
container?.performBackgroundTask { [weak self] context in
self?.wordLists = try! List.all(in: context)
DispatchQueue.main.async(execute: {
print("Main queue available, reloading tableview.")
self?.wordListSelector.reloadData()
})
}
class func all(in context: NSManagedObjectContext) throws -> [List] {
let listRequest: NSFetchRequest<List> = List.fetchRequest()
do {
let list = try context.fetch(listRequest)
print(list)
return list
} catch {
print("error")
throw error
}
}
这张照片:
[<__Words.List: 0x6000000937e0> (entity: List; id: 0xd00000000004000c <x-coredata://999D0158-64BD-44FD-A0B1-AB4EC03B9386/List/p1> ; data: <fault>), <__Words.List: 0x600000093a60> (entity: List; id: 0xd00000000008000c <x-coredata://999D0158-64BD-44FD-A0B1-AB4EC03B9386/List/p2> ; data: <fault>), <__Words.List: 0x600000093ab0> (entity: List; id: 0xd0000000000c000c <x-coredata://999D0158-64BD-44FD-A0B1-AB4EC03B9386/List/p3> ; data: <fault>)]
这说明数据库中应该有3个列表,这是意料之中的。
我创建了这样一个变量:
var wordLists: [List] = [] {
didSet {
print("Detected wordList update, waiting for main queue.")
DispatchQueue.main.async(execute: {
print("Main queue available, reloading tableview.")
self.wordListSelector.reloadData()
})
}
}
此变量保存通过调用前面提到的all()函数检索到的列表实体。
以下两种方法将填充我的TableView:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("numberOfRowsInSection: \(wordLists.count).")
return wordLists.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "CategoryCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
print("cellForRowAt: \(indexPath.row) has name \(wordLists[indexPath.row].name).")
cell.textLabel?.text = wordLists[indexPath.row].name
return cell
}
这将打印以下内容:
Detected wordList update, waiting for main queue.
Main queue available, reloading tableview.
numberOfRowsInSection: 3.
cellForRowAt: 0 has name nil.
cellForRowAt: 1 has name nil.
cellForRowAt: 2 has name nil.
为什么这个名字叫nil?这是因为数据仍然是“故障”的吗?通过在线查看主题,我认为当您试图访问核心数据时,它的数据会自动地不受影响。我做错什么了?
编辑:
如果我将didset更改为以下值:
var wordLists: [List] = [] {
didSet {
print("Wordlist was updated.")
for wordList in wordLists {
print(wordList)
print(wordList.name)
}
}
}
它确实会打印名称(可选(“nameofitem1”)。在牢房里仍然印着“无”。
最佳答案
对于NSFetchedResultsController,您所做的工作看起来很不错。这也将有助于您按照注释中的建议混合线程。关于NSFetchedResultsController
关于swift - 读取核心数据实体的属性值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47112586/