iphone - 将委托(delegate)从 ViewController 分离到自己的类

标签 iphone ios objective-c uiviewcontroller delegates

我是 iOs 开发的新手,我有点困惑我应该如何分离我的代码以避免巨大的 ViewController.m 文件。目前我的主视图 Controller 有很多委托(delegate):

@interface ViewController : UIViewController <MKMapViewDelegate, HttpClientDelegate, CLLocationManagerDelegate, NSFetchedResultsControllerDelegate>

我想减少 viewController 代码,我想我应该创建单独的类来处理委托(delegate)任务。问题是,如果我为 CLLocationManager 创建单例类并让它实现委托(delegate)方法,那么我如何与 View Controller 通信?

假设我的 CLLocationManager 接收到位置更新,我如何告诉 viewController 更改 UI?我应该使用 NSNotificationCenter 发布通知,然后将观察者添加到 View Controller 吗?还是让 viewController 像现在一样实现所有委托(delegate)方法是最好的方法?

最佳答案

将其中一些功能移到您的数据模型中。

鉴于您提供的信息有限,很难说您应该如何管理它,但人们不得不怀疑单个 View Controller 是否真的应该管理 map View 跟踪位置 管理 HTTP 连接 管理核心数据获取。为什么不将其中一些移到您的模型中,这样划分模块会更容易一些?

Let's say that my CLLocationManager receives a location update, how do I tell the viewController to make changes to the UI? Should I use NSNotificationCenter to post a notification and then add observer to the view controller?

通知将是一个很好的解决方案——它为您的程序中管理位置的部分(同样,这可能属于模型)提供了一种方式来传达更改,而无需特别了解有关该部分的任何信息关心位置变化的程序。它还允许一对多通信——如果您有另一个也关心位置的 View Controller ,它可以观察到相同的通知。

Or is the best way just to let viewController implement all delegate methods as it is now?

我尽量考虑适本地划分职责,而不是限制代码的大小。如果您有一个只完成一项工作但需要大量代码才能完成的类,那很好。如果你有一个类来管理许多不相关的事情,那就不太好了。麻烦的是,很多工作似乎都属于传统的 View Controller “管理一屏内容”的角色。尝试将管理数据呈现的任务(这是 View Controller 的合法工作)与管理数据本身(这是模型的工作)分开。

关于iphone - 将委托(delegate)从 ViewController 分离到自己的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18617457/

相关文章:

objective-c - 格式化 float 以填充前导空格

iphone - XML特殊字符解析

iphone - 是否可以将 Android WebView 屏蔽为 iPhone "App Mode"safari 浏览器?

iOS:为 UISwitch 设置默认值

ios - Xcode - 如何将模拟器显示为真实的 iPhone

ios - 在 UITableViewController IOS 中扩展 UIViewController

ios - iPhone游戏,一部手机比另一部手机快

iphone - 登录时的按钮操作 FBConnect API 中的按钮单击

css - 滚动在移动设备 (iPhone) 上不起作用

android - Facebook URL 方案不起作用 fb ://publish