Delegate 与Protocol
在阅读这一章之前,相信你应该已经写过一些简单的iOS程序,知道如果我们想要一个像是系统设定(Setting.app)那样的表格介面,我们会建立UITableViewController
的subclass,这个controller的view是UITableView
。
当我们想要设定表格中的内容,像是这个表格中有多少个section、每个section里头有多少row、每个row里头又是哪些内容…我们不是直接调用UITableView
的method,像是调用[myTableView setSectionCount:3]
或是[myTableView setRowCount:3 atSection:4]
,而是去实现UITableViewController
里头几个像是template method的东西,像numberOfSectionsInTableView:
、tableView:numberOfRowsInSection:
等等。
为什么不是直接去改变view,而是controller要准备一些不知道会被谁调用的method?理由是:UITableViewController
是UITableView
的data source与delegate。那,什么是delegate?
用我的话来说,delegate就是将众多的callback,集中在一个实例上。
如果你还不知道怎么建立Table View或Collection View,请先做完Beginning iOS 7 Development Exploring the iOS SDK这本书的第七章到第十章的相关练习。这本书好像中文只有翻译出iOS 5的版本,叫做《探索iOS 5程式开发实战》,不过章节位置差不多。