Search code examples
iosxcodeuitableviewincompatibletypeerror

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


I'm trying to make an app programmatically that includes a UITableView that makes a list of items based on the files in the app's Documents directory. I have been able to make the files be read into an array _filepathsArray, but the compilation crashes and Xcode throws warnings when I try to use the array to fill the table. Xcode points out problems with the following lines:

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

Both of these throw "semantic issues". The first throws

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

while the second throws

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

If I remove these lines, the app will compile properly (but of course does not use the data to fill the table), so I assume that the problem has to do with these.

I'm a beginner with Objective C and Xcode, so I can't quite figure out what I'm doing wrong here. Thanks for the help.

UPDATE

I have changed the line _tableView.dataSource = _filepathsArray; to _tableView.dataSource = self; as explained by several answers below. Now, both lines throw the same error:

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

Could this error be the result of the way that the view controller is configured? In the header file, it is defined as a UIViewController

@interface BrowserViewController : UIViewController

I then include a UITableView as a subview.


Solution

  • You should declare a UITableViewDataSource, which is an object that implements that protocol and supplies data to your table.

    _tableView.dataSource = self;
    

    From 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.
    

    Updated: Please define your class like below as per my first line in the answer that You should declare a UITableViewDataSource:

    @interface BrowserViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>