iOS和Xcode:在UITableView中设置委托和数据源时不兼容的types错误

我试图编程的应用程序,其中包括一个UITableView,根据应用程序的文档目录中的文件制作项目列表。 我已经能够将文件读入一个数组_filepathsArray ,但是当我尝试使用数组填充表时,编译崩溃和Xcode抛出警告。 Xcode指出了以下几行的问题:

 _tableView.delegate = self; _tableView.dataSource = _filepathsArray; 

这两个都会抛出“语义问题”。 第一个抛出

 `Assigning to 'id<UITableViewDataSource>' from incompatible type 'NSArray *__strong'`, 

而第二个抛出

 `Assigning to 'id<UITableViewDelegate>' from incompatible type 'BrowserViewController *const __strong'`. 

如果我删除这些行,应用程序将正确编译(但当然不会使用数据来填充表),所以我认为这个问题与这些。

我是Objective C和Xcode的初学者,所以我无法弄清楚我在这里做错了什么。 谢谢您的帮助。

UPDATE

我改变了行_tableView.dataSource = _filepathsArray; to _tableView.dataSource = self; 正如下面几个答案所解释的。 现在,两行都会抛出相同的错误:

 `Assigning to 'id<UITableViewDelegate>' from incompatible type 'BrowserViewController *const __strong'`. 

这个错误可能是视图控制器configuration的结果吗? 在头文件中,它被定义为一个UIViewController

 @interface BrowserViewController : UIViewController 

然后我包含一个UITableView作为子视图。

您应该声明一个UITableViewDataSource ,它是一个实现该协议并将数据提供给您的表的对象。

 _tableView.dataSource = self; 

从苹果文件

 dataSource The object that acts as the data source of the receiving table view. @property(nonatomic, assign) id<UITableViewDataSource> dataSource Discussion The data source must adopt the UITableViewDataSource protocol. The data source is not retained. 

更新:请按照下面的定义你的类,根据我的第一行你应该声明一个UITableViewDataSource

 @interface BrowserViewController : UIViewController <UITableViewDataSource,UITableViewDelegate> 

您会收到这些警告,因为您没有声明要在要作为数据源和委托的对象的.h文件中实现数据源和委托方法。 通常,这将是UITableViewController或UIViewController的子类,但是实现协议的任何对象都可以是数据源或委托。 一个UITableViewController已经符合这两个协议,所以你不需要声明任何东西,但是如果你正在使用一个UIView控制器,你应该把这个(尽pipe这不是必须的)在.h文件中:

 @interface YourCustomClassName : UIViewController <UITableViewDataSource,UITableViewDelegate> 

在.m文件中,您应该将self设置为数据源和委托(同样,这是通常的模式,但是一个对象不必同时提供这两个angular色):

 self.tableView.delegate = self; self.tableView.dataSource = self; 

_tableView.dataSource = _filepathsArray; // < – 这是问题,因为它的types是控制器不是数组,

 // add this to your interface @interface BrowserViewController : UIViewController <UITableViewDataSource,UITableViewDelegate> 

因为你目前没有确认UITableView协议

总是使用这个样子

 _tableView.delegate = self; _tableView.dataSource = self; 

而您的_filepathsArray将用于numberofRows委托获取行数和int cellForRowIndexPath来显示数据

 cell.titleLabel.text = _filepathsArray[indexPath.row]; 
Interesting Posts