注:答案见底部“编辑”。
我正在编写一个自定义的NSObject,它将异步初始化自己,然后在它完成时发送一个NSNotification,以便我可以将它附加到我的UITableView的数据源中。这是课堂:

class Friend: NSObject {
var userID: String!
var schedule: Schedule!

init(friendUserID: String) {
    super.init()
    print("Initializing Friend.")
    self.userID = friendUserID
    let notificationIdentifier = friendUserID + "hasFinishedDownloading"
    print("Adding observer for:", notificationIdentifier)
    nc.addObserver(self, selector: #selector(haveFinishedDownload), name: Notification.Name(notificationIdentifier), object: nil)
    let friendSchedule = Schedule(userID: friendUserID)
    self.schedule = friendSchedule
}

@objc func haveFinishedDownload(notification: Notification) {
    print("Download Finished.")
    print(notification)
}
}

在添加观察者时,我为“selector”属性尝试了几种不同的方法,但运气很差。
以下是发送通知时的代码:
class Schedule: NSObject {

//The Key is what day it meets period 4
//The value is an SSAClass object
var ssaClassesDictionary:Dictionary<Int, SSAClass> = [:]

func addClassToDicitonary(classObject: SSAClass!) {
    self.ssaClassesDictionary[classObject.day!] = classObject
}

func fillClasses(userID: String!) {
    print("Filling Classses")
    var userOrTeacher: String!

    switch isUserTeacher(user: userID) {
    case true:
        userOrTeacher = "Teachers"
    case false:
        userOrTeacher = "Users"
    }
    print("Ref about to run")
    ref.child(userOrTeacher).child(userID!).child("c").observe(.value, with: {(snapshot) in
        print("Ref has started downloading")

        if (snapshot.value != nil) {
            let snapshotValue: [String] = snapshot.value as! [String]
            print("snapshot.value != nil")
            var numberDownloaded = 0

            for i in snapshotValue {
                print("running for loop iteration:", i)
                ref.child("Classes").child(i).observeSingleEvent(of: .value, with: {(snapshot) in

                    let value = snapshot.value as! Dictionary<String, Any>

                    //"year", "1", "2", or "3"
                    var customTerm: String!

                    //"year", 1, 2, or 3
                    let term = value["term"]
                    switch term {
                    case is String.Type:
                        customTerm = "year"
                    case is Int.Type:
                        customTerm = "\(term!)"
                    default: customTerm = "year"
                    }

                    let ssaClass = SSAClass(classID: i, AB: value["AB"] as! Bool, Sci: value["Sci"] as! Bool, name: value["n"] as! String, room: value["room"] as! String, term: customTerm, day: value["d"] as! Int)
                    if ssaClass.term == "year" || ssaClass.term == "3" {
                        self.addClassToDicitonary(classObject: ssaClass)
                    }

                    numberDownloaded = numberDownloaded + 1
                })
            }

            DispatchQueue.global(qos: .background).async {
                //This is run on the background queue
                print("Running asynchronous Code")
                while numberDownloaded < snapshotValue.count {
                }

                DispatchQueue.main.async {
                    print("Finished While Loop, going back to main thread")
                    //This is run on the main queue, after the previous code in outer block
                    //Post notification
                    let notificationIdentifier = userID + "hasFinishedDownloading"
                    print("Posting Notification for:", notificationIdentifier)
                    nc.post(name: Notification.Name(notificationIdentifier), object: nil)
                }
            }

        }

    })
}


init(userID: String!) {
    super.init()
    fillClasses(userID: userID)
}
}

所有打印输出运行:
Initializing Friend.
Adding observer for: 19wangdhasFinishedDownloading
Filling Classses
Ref about to run
Default
Ref has started downloading
snapshot.value != nil
running for loop iteration: CH402 - 1
running for loop iteration: CH404 - 1
running for loop iteration: CH406 - 2
running for loop iteration: CS400 - 11
running for loop iteration: CS411 - 11
running for loop iteration: EN301 - 3
running for loop iteration: EN302 - 1
running for loop iteration: EN4014 - 2
running for loop iteration: FR360 - 1
running for loop iteration: HI300 - 8
running for loop iteration: MA405 - 2
running for loop iteration: MA406 - 1
running for loop iteration: MA501 - 2
running for loop iteration: MA506 - 1
Running asynchronous Code
Finished While Loop, going back to main thread
Posting Notification for: 19wangdhasFinishedDownloading

除了“下载完成”。
非常感谢大家的帮助。
编辑:接受的答案指出了问题所在。我只是测试我的代码,而没有在任何地方实现初始化的类。结果,为了保存记忆,ARC用我的朋友对象做了一些事情。出于测试的目的,我把它附加到一个全局数组中,并在应用程序中的任意按钮被按下时打印数组的内容,使ARC认为我在某种程度上使用了它。

最佳答案

您的Friend实例可能已被ARC自动释放。你有很强的参考价值吗?
将这些行添加到Friend类中以进行检查:

deinit {
    print("\(userID) deallocated")
}

关于swift - 在NSObject中收到NSNotification时的调用方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49225278/

10-12 18:08