Make code with Firebase asynchronous

前端 未结 1 1549
太阳男子
太阳男子 2020-12-12 07:03

I am trying to create an algorithm that creates 12 struct objects(question) and puts them in an array(questions). However, it doesn\'t seem to work as the objects are create

相关标签:
1条回答
  • 2020-12-12 07:42

    When this happens, the solution is usually to move the operation inside the callback:

    databaseRef.child("questions").child("questionNumber: " + questionNum).child("title").observeSingleEvent(of: .value, with: { snapshot in
        print(snapshot.value ?? "")
        question.title = (snapshot.value as? String)!
    
        databaseRef.child("questions").childSnapshot(forPath: "questionNumber: " + questionNum).childSnapshot(forPath: "description").observeSingleEvent(of: .value, with: { snapshot in
            print(snapshot.value ?? "")
            question.desc = (snapshot.value as? String)!
            self.questions.append(question)
        })
    })
    

    But in this case I wonder why you don't simply load the entire question in one go:

    FIRDatabaseReference qref = databaseRef.child("questions").child("questionNumber: " + questionNum)
    qref.observeSingleEvent(of: .value, with: { snapshot in
        var question = questionMGR()
        question.title = (snapshot.childSnapshot(forPath: "title").value as? String)!
        question.desc = (snapshot.childSnapshot(forPath: "description").value as? String)!
        self.questions.append(question)
    })
    

    The only reason I'd ever consider two separate calls for title and description is if your questions contain a lot more data that you don't need here. But if that's the case, I'd remodel your JSON to separate the title and description into a separate top-level list.

    In NoSQL it's often a Good Thing (tm) to model your data to be very similar to what you show on the screen. So if you have a list if the title and description of each question, you should consider storing precisely that: a list of the the title and description for each question.

    0 讨论(0)
提交回复
热议问题