我有一对多的数据库(问题--->>按钮) 我被困在这里,因为我不知道如何继续从我的数据库访问按钮:
我有以下代码可以访问我的Questions
实体,但我不知道如何从这里开始。感谢
func presentQuestionDetails(questionID :Int) {
let coreDataStack = CoreDataStack()
managedObjectContext = coreDataStack.persistentContainer.viewContext
let fetchRequest: NSFetchRequest<Questions> = Questions.fetchRequest()
let myPredicate = NSPredicate(format: "%K == %i", "questionID", questionID)
fetchRequest.predicate = myPredicate
do {
let results = try managedObjectContext!.fetch(fetchRequest)
if results.isEmpty {
//empty
print("empty")
}
else {
let question = results[0]
//do something
print("got something")
questionLabel.text = question.questionTitle
for _ in 0..<(question.buttons?.count)! {
//I'D LIKE TO LOOP THROUGH MY BUTTONS HERE AND ACCESS MY "buttonTitle" i.e print(buttons.buttonTitle!)
}
}
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
答案 0 :(得分:0)
这是正确的方法吗?我只是猜测,并希望你的意见。 它似乎提供了正确的结果,但我不确定这是否是正确的方法......
感谢
[...]
else {
let question = results[0]
//do something
print("got something")
questionLabel.text = question.questionTitle
let fetchRequest: NSFetchRequest<Buttons> = Buttons.fetchRequest()
let myPredicate = NSPredicate(format: "%K == %i", "questions", questionID)
fetchRequest.predicate = myPredicate
do {
let results = try managedObjectContext!.fetch(fetchRequest)
for buttons in results {
print(buttons.buttonTitle!)
}
}
catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}