简体   繁体   English

Swift NSNotificationCenter在其他类中添加观察者函数

[英]Swift NSNotificationCenter add observer func in other class

I have ViewContoller , download class and class for work with data in ViewContoller need call method for download data from internet, after NSNotificationcenter send complete message, and work class with data, after in my table I use reload data 我有ViewContoller ,在ViewContoller中下载数据的类和用于处理数据的类需要从Internet上下载数据的调用方法,在NSNotificationcenter发送完整的消息后,并使用数据处理类,在我的表中使用重载数据之后

Problem - notifCenter.postNotificationName("completeLoadService", object: complete) Thread1: EXC_BAD_ACCESS (code = 1, address = 0x10) 问题notifCenter.postNotificationName("completeLoadService", object: complete) Thread1: EXC_BAD_ACCESS (code = 1, address = 0x10)

    override func viewDidLoad() {
    super.viewDidLoad()

    ServicesLoad.loadServicesFromSite()

    let center : NSNotificationCenter = NSNotificationCenter.defaultCenter()

    var load : LoadServiceTrainersAreasClubs = LoadServiceTrainersAreasClubs()

    center.addObserver(load, selector: Selector("loadService:"), name: "completeLoadService", object: nil)
}

download class 下载类

        operation.setCompletionBlockWithSuccess({
        (operation : AFHTTPRequestOperation!, servicesData : AnyObject!) -> Void in

       //some code

            var complete  : Bool = Bool()
            complete = true

            var notifCenter : NSNotificationCenter = NSNotificationCenter.defaultCenter()
            notifCenter.postNotificationName("completeLoadService", object: complete)

        })

class work with data LoadServiceTrainersAreasClubs 类与数据LoadServiceTrainersAreasClubs一起使用

func loadService(notif : NSNotification){

    println("complete")

}

LoadServiceTrainersAreasClubs is a local variable. LoadServiceTrainersAreasClubs是一个局部变量。 You do not have a strong reference to it. 您对此没有很强的参考。 It will be deallocated as soon as the viewDidLoad method exits. 一旦viewDidLoad方法退出,它将被释放。 NSNotificationCenter keeps observers as weak references. NSNotificationCenter将观察者作为弱引用。 Therefore, it looks like NSNotificationCenter is attempting to notify your configured observer, but it has been deallocated which is causing the crash. 因此,NSNotificationCenter似乎正在尝试通知您配置的观察者,但已被释放,从而导致崩溃。

Also, I would recommend against using notification center for something like this. 另外,我建议不要将通知中心用于此类操作。 I would suggest using a block or delegate to inform the consumer of this service completion. 我建议使用一个块或委托来通知用户此服务的完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM