为什么在观察块内部打印(计数)之前执行外部观察块打印?

时间:2018-11-16 03:32:51

标签: ios swift firebase firebase-realtime-database

func teacherExists(teacherName: String) -> Bool
    {
        var dataBaseRef2: DatabaseReference!
        dataBaseRef2 = Database.database().reference()
        let teachersTableRef = dataBaseRef2.child("teachers")
        self.teachersList.removeAll()
        teachersTableRef.observeSingleEvent(of: DataEventType.value, with: { (snapshot) in

       // teachersTableRef.observe(.value)
        //{
          //  snapshot in
            let teachersNamesDictionary = snapshot.value as? [String: Any] ?? [:]
            for(key, _) in teachersNamesDictionary
            {
                if let teacherDict = teachersNamesDictionary[key] as? [String: Any]
                {
                    if let teacher = Teacher(dictionary: teacherDict)
                    {
                        //print(teacher.teacher_name)
                        self.teachersList.append(teacher.teacher_name)
                    }
                }
            }
            print(self.teachersList.count)
        })
        print("Outside \(self.teachersList)")
        return false
    }

3 个答案:

答案 0 :(得分:2)

因为Firebase APIs are all asynchronous。如果它们阻止了您的代码路径,那将对您的应用程序不利,因为这可能导致您的应用程序无限期挂起。

observeSingleEvent立即返回 ,并且只要数据准备好,传递的观察者就会在一段时间后被调用。在下一行继续执行,并打印到控制台。

答案 1 :(得分:0)

检查重复项后,可以使用闭包进行回调

func teacherExists(teacherName: String, completion: @escaping ((Bool) -> Void)) -> Void {
    var dataBaseRef2: DatabaseReference!
    dataBaseRef2 = Database.database().reference()
    let teachersTableRef = dataBaseRef2.child("teachers")
    self.teachersList.removeAll()
    teachersTableRef.observeSingleEvent(of: DataEventType.value, with: { (snapshot) in

        let teachersNamesDictionary = snapshot.value as? [String: Any] ?? [:]
        for(key, _) in teachersNamesDictionary
        {
            if let teacherDict = teachersNamesDictionary[key] as? [String: Any]
            {
                if let teacher = Teacher(dictionary: teacherDict)
                {
                    //print(teacher.teacher_name)
                    self.teachersList.append(teacher.teacher_name)
                }
            }
        }
        let exists = self.teachersList.contains(teacherName)
        completion(exists)
    })
}

并如下调用函数

teacherExists(teacherName: newTeacherName) { (exists) in
    if exists {
        // show alert
    } else {
        // add new teacher to db
    }
}

希望有帮助!

答案 2 :(得分:0)

  

在调用TeacherExists函数时出错

data = {(1, 2), (1, 4), (2, 2), (0, 3), (0, 4)}

data_1 = sorted(data, key=lambda x: x[0], reverse=True)

data_2 = sorted(data_1, key=lambda x: x[1])

>>> print(data_2)
[(2, 2), (1, 2), (0, 3), (1, 4), (0, 4)]

# desired output
[(2, 2), (1, 2), (1, 4), (0, 3), (0, 4)]