【问题标题】:Communication between Model and Controller模型和控制器之间的通信
【发布时间】:2014-09-10 00:06:17
【问题描述】:

从许多不同的来源阅读后,我对 View 和 Model 应该如何在 MVC 中使用 Swift 进行通信感到非常困惑

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

在模型中:

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

在视图控制器中处理“ReceivedData”通知:

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

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

【问题讨论】:

    标签: ios model-view-controller swift


    【解决方案1】:
    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!");
    }
    

    【讨论】:

    • 省略-> () 更简洁。
    • 带选择器:“receivedDataNotification:”
    【解决方案2】:

    在 Swift 中,您可以在属性声明中使用“didSet”闭包来在变量更改时通知 viewController。

    就如何进行通知而言,使用 NSNotificationCenter(上面的答案)或委托(模型中的协议,在 viewController 中实现)都可以。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-04-27
      • 1970-01-01
      • 1970-01-01
      • 2012-08-10
      • 1970-01-01
      • 2011-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多