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

Ios Swift NSNotificationCenter在其他类中添加观察者函数,ios,iphone,xcode,swift,Ios,Iphone,Xcode,Swift,我有ViewContoller,下载类和类来处理数据 在ViewContollerneed call method中,从internet下载数据,在NSNotificationcenter发送完整消息后,使用数据工作类,在我的表中使用重新加载数据后 问题-notifCenter.postNotificationName(“completeLoadService”,对象:complete)线程1:EXC\u错误访问(代码=1,地址=0x10) 下载类 operation.setCo

我有
ViewContoller
,下载类和类来处理数据 在
ViewContoller
need call method中,从internet下载数据,在
NSNotificationcenter
发送完整消息后,使用数据工作类,在我的表中使用重新加载数据后

问题-
notifCenter.postNotificationName(“completeLoadService”,对象:complete)线程1:EXC\u错误访问(代码=1,地址=0x10)

下载类

        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)

        })
使用数据加载服务TrainersAreasCrubs进行课堂教学

func loadService(notif : NSNotification){

    println("complete")

}

LoadServiceTrainersAreasClubs是一个局部变量。你没有很强的参考价值。一旦viewDidLoad方法退出,它就会被释放。NSNotificationCenter将观察者保留为弱引用。因此,NSNotificationCenter似乎正在尝试通知您配置的观察者,但它已被解除分配,导致崩溃


另外,我建议不要使用通知中心进行类似的操作。我建议使用块或委托通知消费者此服务已完成。

变量名为
load
LoadServiceTrainersAreasClubs
。但您的结论是正确的:在发送通知时对象已解除分配。但为什么“像这样”使用通知中心是个坏主意呢?在我看来,对于简单的1对1关系,NSNotificationCenter被过度使用了。这是一种观察者设计模式解决方案,通常用于1对多关系。它可能会导致混乱,而作为回调机制使用的块/闭包会鼓励更可读的代码。对于1:1关系,我完全同意您的看法,这就是委托模式的用途。
func loadService(notif : NSNotification){

    println("complete")

}