把委托方法放到一个类别中

我到现在为止开发了一些应用程序。 现在我正在写一个新的,在这个项目中我想保持代码非常干净,所以很容易find方法。
我想从UIViewControllers开始,它的视图有一个UITableView作为子视图。 我希望有一个名为DetailViewController的文件,用于直接属于它的所有function。 另一个名为DetailViewController+Protocols文件应该包含上面类的一个类和UITableView的所有这些委托方法。

有没有可能做这样的事情? 我想保持我的代码干净,并将其分割成多个文件。


编辑

DetailViewController.h

 @interface DetailViewController : UIViewController ... Some Properties ... Some Methods @end 

DetailViewController.m

 #import "DetailViewController.h" @implementation DetailViewController ... Some Synthesizes ... Some Methods @end 

DetailViewController + Protocols.h

 @interface DetailViewController (Protocols) <UITableViewDelegate, UITableViewDataSource> @end 

DetailViewController + Protocols.m

 @implementation DetailViewController (Protocols) - (NSINteger)numberOfSections { return ...; } - (NSInteger)numberOfRowsInSection:(NSInteger)section { if (section == 0) return ...; return ...; } ... @end 

但是,然后Xcode显示了一些警告,一些委托方法没有在DetailViewController中实现。 我也试过在DetailViewController.h中导入DetailViewController + Protocols.h 。 没有变化。
然后我试着忽略这些警告,看看:它的工作! 但为什么? 没有这些警告,它不应该工作吗?

是的。 唯一要记住的类别是你不能@synthesize属性。 在类别中添加ivars也比较困难。

看到这个更多的信息。

如果您只是针对一个类使用它,则不必在其他文件中创build完全独立的命名协议。 事实上,你可能不应该,因为这只是混乱。

如果你想保持你的主类'.h文件干净,只要移动它:

 @interface DetailViewController (Protocols) <UITableViewDelegate, UITableViewDataSource> @end 

到@implementation上面的主要.m文件中

我不明白为什么你不想在你的.h中声明你的主类实现了tableview委托和数据源协议。 他们是描述性的。