我試圖讓我的視圖控制器保持乾淨,如本文所述objc.io Issue #1 Lighter View Controllers。我在Objective-C中測試了這個方法,它工作正常。我有一個單獨的類實現UITableViewDataSource
方法。將數據源分離到Swift中的另一個類
#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中的數據源和它完美的作品。
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:]:無法識別的選擇發送到實例
我檢查的TableDataSource
的init
方法和項目和小區標識符被傳遞細。我不得不聲明UITableViewDataSource
方法public
並刪除override
關鍵字,否則會導致編譯時錯誤。
我對這裏出了什麼問題毫無頭緒。任何人都可以請幫我嗎?
謝謝。
可以在崩潰時顯示堆棧跟蹤嗎? – 2014-09-11 13:56:02
看起來您的數據源未被保留。你在哪裏存儲參考? – jlehr 2014-09-11 14:39:13
@jlehr這確實是問題所在。我不想保存它!我做了一個屬性'var dataSource:TableDataSource!'並將其分配給tableview的'dataSource'屬性,它現在可以工作:)謝謝。 – Isuru 2014-09-11 16:20:08