Я пытаюсь очистить контроллеры своего вида, как описано в этой статье objc.io Issue # 1. Я протестировал этот метод в Objective-C, и он отлично работает. У меня есть отдельный класс, который реализует методы UITableViewDataSource
.
#import "TableDataSource.h"
@interface TableDataSource()
@property (nonatomic, strong) NSArray *items;
@property (nonatomic, strong) NSString *cellIdentifier;
@end
@implementation TableDataSource
- (id)initWithItems:(NSArray *)items cellIdentifier:(NSString *)cellIdentifier {
self = [super init];
if (self) {
self.items = items;
self.cellIdentifier = cellIdentifier;
}
return self;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.items.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath];
cell.textLabel.text = self.items[indexPath.row];
return cell;
}
@end
В контроллере tableview все, что мне нужно сделать, это создать экземпляр этого класса и установить его как источник данных tableview, и он отлично работает.
self.dataSource = [[TableDataSource alloc] initWithItems:@[@"One", @"Two", @"Three"] cellIdentifier:@"Cell"];
self.tableView.dataSource = self.dataSource;
Теперь я пытаюсь сделать то же самое в Swift. Сначала здесь мой код. Это в значительной степени перевод кода Objective-C выше.
import Foundation
import UIKit
public class TableDataSource: NSObject, UITableViewDataSource {
var items: [AnyObject]
var cellIdentifier: String
init(items: [AnyObject]!, cellIdentifier: String!) {
self.items = items
self.cellIdentifier = cellIdentifier
super.init()
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = items[indexPath.row] as? String
return cell
}
}
И я называю это так.
let dataSource = TableDataSource(items: ["One", "Two", "Three"], cellIdentifier: "Cell")
tableView.dataSource = dataSource
Но приложение вылетает со следующей ошибкой.
- [NSConcreteNotification tableView: numberOfRowsInSection:]: непризнанный селектор, отправленный в экземпляр
Я проверил метод init
TableDataSource
, и элементы и идентификатор ячейки передаются в порядке. Мне пришлось объявить методы UITableViewDataSource
public
и удалить ключевое слово override
, иначе оно даст ошибки времени компиляции.
Я не знаю, что здесь происходит. Кто-нибудь может помочь мне?
Спасибо.