简体   繁体   中英

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

Problem - 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

func loadService(notif : NSNotification){

    println("complete")

}

LoadServiceTrainersAreasClubs is a local variable. You do not have a strong reference to it. It will be deallocated as soon as the viewDidLoad method exits. NSNotificationCenter keeps observers as weak references. Therefore, it looks like NSNotificationCenter is attempting to notify your configured observer, but it has been deallocated which is causing the crash.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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