模型与控制器之间的通信

时间:2014-07-18 18:59:23

标签: ios model-view-controller swift

从许多不同来源阅读后,我对如何在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!");
}

2 个答案:

答案 0 :(得分:5)

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!");
}

答案 1 :(得分:1)

在Swift中,您可以使用" didSet"在属性声明中闭包,以便在变量发生变化时通知viewController。

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

希望这有帮助。