iOS协议和代理。基本问题 [英] iOS protocols and delegates. Basic questions

查看:156
本文介绍了iOS协议和代理。基本问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个具有UITableView的应用程序。



数据将通过网络获取的XML进行转换。我正在使用NSXMLParser,它的工作原理。我使用我的tableView控制器作为代理,所以它实现它的协议:

  @protocol NSXMLParserDelegate; 
@interface MainView:UITableViewController< NSXMLParserDelegate>

现在这样做完美,因为我已经记录了所得到的解析。
现在,我想填充NStableView,所以阅读我发现我需要添加数据源和委托。

  UITableViewDataSource 

  UITableViewDelegate 

这两个都是协议。



我如何在同一班上做这个?我可以用相同的类实现多个协议吗?我应该将解析器的代理移动到另一个对象,并为此目的使用此控制器?



基本上问题是最好的方法是什么? >

谢谢

解决方案

当然可以在类中实现多个协议如你所愿:

  @interface MainView:UITableViewController< NSXMLParserDelegate,UITableViewDataSource,UITableViewDelegate> 

这样做是适当的方式吗?我不认为这是一个正确的答案。纯粹主义者可能会说不。我会说这样做是有意义的,但是错误地将其分解成单独的类。例如,如果您的视图控制器是一个简单的菜单,那么您的视图控制器也可以是您的表视图委托和数据源;没有任何优势将其分解成多个类。



如果您必须解析XML,我的直觉表明它开始变得更复杂了。也许有一个数据类实现数据源和XML解析器和控制器类?


I'm creating an app that has a UITableView.

The data will be comming from an XML fetched over the net. I'm using NSXMLParser for this and it works. I used my tableView controller as the delegate for this so it implements the protocol for it:

@protocol NSXMLParserDelegate;
@interface MainView : UITableViewController <NSXMLParserDelegate>

Now this works perfectly, as I've nslogged the resulting parse. Now, I want to populate the NStableView, so Reading I find that I need to add the datasource and delegate.

UITableViewDataSource

and

UITableViewDelegate

both of which are protocols.

How would I go about doing this on the same class? can I implement more than one protocol with the same class? should I move the delegation of the parser to another object and use this controller for this purpose?

Basically the question is what is the best way to do this?

thank you

解决方案

Sure, you can implement as many protocols in a class as you want:

@interface MainView : UITableViewController <NSXMLParserDelegate, UITableViewDataSource, UITableViewDelegate>

Is that the "proper" way of doing that? I don't think there's a "right" answer to that. A purist might say no. I'd say do it where is makes sense, but err on the side of breaking it out into separate classes. For example, if your view controller is a simple menu then it would make sense for your view controller to also be your table view delegate and data source; there's no advantage in breaking it out into multiple classes.

If you have to parse XML my intuition suggests that it's starting to get a bit more complex. Maybe have a data class that implements the data source and XML parser and a controller class?

这篇关于iOS协议和代理。基本问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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