ios - 模型和 Controller 之间的通信

标签 ios model-view-controller swift

从许多不同的来源阅读后,我很困惑 View 和 Model 应该如何在 MVC 中与 Swift 通信

如何用 Swift 做同样的事情(在 objective-c 中)

在模型中:

(void)receivedMessageFromServer {
    // Fire the notification
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ReceivedData" object:nil];   
} 

在 View Controller 中处理“ReceivedData”通知:

(void)viewDidLoad {
    [NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedDataNotification:) name:@"ReceivedData" object:nil];
}

-(void)receivedDataNotification:(id)object {
    NSLog(@"Received Data!");
}

最佳答案

func receivedMessageFromServer() {
    NSNotificationCenter.defaultCenter().postNotificationName("ReceivedData", object: nil)
}

override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "receivedDataNotification:", name: "ReceivedData", object: nil)
}

func receivedDataNotification(object: AnyObject) {
    println("Received Data!");
}

关于ios - 模型和 Controller 之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24831994/

相关文章:

javascript - window.location和$ location.path有什么区别?

ruby-on-rails - 如何在事件提要中显示个人资料照片?

ios - Swift 'open' 关键字和扩展中的可覆盖方法/属性?

iOS 应用程序评论 - 视频流 MPEG-DASH 时间超过 10 分钟

c# - 如何使用 Autofac 解决属性注入(inject)问题?

ios - 无法使用类型为 '[String]' 的索引下标类型为 'Int' 的值

arrays - 与 map 方法相比,为什么这种 for 循环方法这么慢?

ios - Firebase 推送通知在收到通知时增加角标(Badge)计数

ios - Iphone X 中 Tabbar 下方部分的高度

ios - swift - 使用委托(delegate)方法的返回值来设置变量