【问题标题】:Access one to many CoreData with predicate使用谓词访问一对多 CoreData
【发布时间】:2017-05-09 06:35:43
【问题描述】:

我有一个一对多的数据库(问题--->>按钮) 我被困在这里,因为我不知道如何继续访问数据库中的按钮:

我有以下代码可以访问我的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)")
        }



    }

【问题讨论】:

    标签: sqlite core-data swift3 nspredicate


    【解决方案1】:

    这是正确的方法吗?我只是在猜测,并希望得到您的意见。 它似乎提供了正确的结果,但我不确定这是否是正确的方法......

    谢谢

    [...]
    
     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)")
                    }    
    
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-26
      • 2011-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多