iOS模型层通知Controller对象 [英] iOS model layer notifying Controller Object

查看:64
本文介绍了iOS模型层通知Controller对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

https://developer.apple .com/library/mac/#documentation/General/Conceptual/DevPedia-CocoaCore/MVC.html

在上面的链接中,我看到以下有关模型层应如何与ViewController通信的信息.

当模型对象发生更改(例如,通过网络连接接收到新数据)时,它将通知控制器对象,该对象将更新相应的视图对象."

我的问题是,模型对象如何通知Controller对象?这种方法有哪些?我的模型层获取用户的位置,然后调用Web服务.下载该数据后,我应如何通知控制器对象?

谢谢

解决方案

有几种方法可以执行此操作,具体取决于您的具体情况.通常,您将使用协议/代理实现,键值观察或通知.在此处.. >

我应该添加一个想法,正如对此答案的评论所提到的:根据您的需要,使用回调块也是一个非常可靠的选择.关于哪种解决方案最适合哪种情况,有很多可能的决定因素,但这是我遵循的一般概述.

如果保证您一次只需要一个观察者:我通常使用块或委托.我个人的喜好是,如果只有一个或两个回调,那么我将使用块,因为这是它们的亮点;但是,如果存在多个可能的方法,那么我将使用委托协议.

如果您可能需要多个观察者,我会通过NSNotificationCenter使用通知.

当我只需要观察实例上的特定属性而不是事件时,就使用键值观察.

https://developer.apple.com/library/mac/#documentation/General/Conceptual/DevPedia-CocoaCore/MVC.html

At the above link, I see the following in regards to how the model layer should communicate with the ViewController.

"When a model object changes (for example, new data is received over a network connection), it notifies a controller object, which updates the appropriate view objects."

My question is, how does the model object notify the Controller object? What are various ways this can be done? My model layer gets the user's location and then calls a web service. How should I notify the controller object when that data is downloaded?

Thanks

解决方案

There are several ways to do this, depending on your specific case. Generally you would use a protocol/delegate implementation, key value observing, or notifications. There is a pretty good overview here.

Edit:

Thought I should add, as the comment to this answer mentioned: using callback blocks is also a very solid option, depending on your needs. There are a lot of possible deciding factors on what solutions are best for what cases but here is a general outline I follow.

If you are guaranteed to only need one observer at a time: I generally use blocks or delegates. My personal preference is that I use blocks if there are only one or two callbacks because this is where they shine, but I use delegate protocols if there more than a few possible methods.

If you may need multiple observers, I use notifications via NSNotificationCenter.

I use Key-Value-Observing when I only need to observe specific properties on an instance, instead of events.

这篇关于iOS模型层通知Controller对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆