繁体   English   中英

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

[英]iOS and Xcode: incompatible type error when setting delegate and datasource in a UITableView

我正在尝试以编程方式制作一个包含UITableView的应用程序,该UITableView根据该应用程序的Documents目录中的文件列出项目列表。 我已经能够将文件读入_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的初学者,所以我不太清楚自己在做什么错。 谢谢您的帮助。

更新

我已经更改了_tableView.dataSource = _filepathsArray;_tableView.dataSource = _filepathsArray; _tableView.dataSource = self; 如以下几个答案所述。 现在,两行都抛出相同的错误:

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

此错误可能是视图控制器配置方式的结果吗? 在头文件中,将其定义为UIViewController

@interface BrowserViewController : UIViewController

然后,我将UITableView包含为子视图。

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

_tableView.dataSource = self;

从Apple Docs

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>

_tableView.dataSource = _filepathsArray; // <-这是问题所在,因为它的类型是控制器而不是数组,

// 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];

之所以收到这些警告,是因为您没有声明要在要成为数据源和委托的对象的.h文件中实现数据源和委托方法。 通常,这将是UITableViewController或UIViewController的子类,尽管实现协议的任何对象都可以是数据源或委托。 UITableViewController已经符合这两个协议,因此您无需声明任何内容,但是,如果您使用的是UIView控制器,则应将其(尽管不是必须的)放在.h文件中:

@interface YourCustomClassName : UIViewController <UITableViewDataSource,UITableViewDelegate> 

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM