我有一个带自定义单元格的UITableView:
标题,标签,文字
这些是UITextView的3个元素,现在我的核心数据中有一个实体:
我想把标题中的标题,标签中的日期和文本中的introText:
我这样做了:
do{
var request = NSFetchRequest<NSFetchRequestResult>(entityName: "Actualites")
let count = try context.count(for: request)
if (count == 0) {
REST().SaveArticles(limit: 5, limitstart: 0, catid: 6, key: "xxx", context: context)
} else {
var actualites = [Actualites]()
actualites = try context.fetch(request) as! [Actualites]
let cell:ActuTblCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! ActuTblCell
for actualites in actualites {
print(actualites.title)
}
}
}catch{
print(error)
}
我可以在循环中获取标题,但如何显示数据?我是否必须创建3个数组?
编辑: 我想我必须在这里做一个循环吗?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ActuTblCell
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy HH:mm"
cell.titleActuCell.text = actualites[indexPath.row].title
cell.dateActuCell.text = formatter.string(from: actualites[indexPath.row].created! as Date)
cell.descriptionActuCell.text = actualites[indexPath.row].introText
return cell
}
线程1:致命错误:索引超出范围
答案 0 :(得分:0)
In your view controller keep an array of Actualites
: var actualites = [Actualites]()
. Then your else
block would look like this:
else {
actualites = try context.fetch(request) as! [Actualites]
tableview.reloadData()
}
You should implement the UITableViewDataSource
protocol to return the number of cells based on the actualites
array, and in the tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
you get the actuality for every cell by this statement: let actuality = actualites[indexPath.row]
and display in the appropriate cell.