在tableview单元格上打印CoreData

问题描述 投票:0回答:2

我这里有2个不同的测试用例。在案例1中,这是我用来从CoreData打印全部条目的工作。我试过在app2中做同样的事情,但它不起作用。我想要做的就是在每个单独的单元格中包含所有核心数据条目。

APP1

override func viewDidLoad() {
    super.viewDidLoad()
    user = coreDataHandler.getSortedData()

    for i in user! {
        displayL.text = String(i.username)
    }
}

APP2

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    user = coreDataHandler.getSortedData()

    return user!.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = cctv.dequeueReusableCell(withIdentifier: "cell")

    for i in user! {
        cell?.textLabel?.text = String(describing: i.username)
        return cell!
    }

    return cell!
}
ios swift uitableview core-data tableview
2个回答
0
投票

如果你想打印每个单元格中的所有用户条目,那么你可以尝试下面的解决方案,

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    user = coreDataHandler.getSortedData()

    return user!.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")

    for i in user! {
        cell?.textLabel?.text = String(describing: i.username)
    }

    return cell!
}

如果你想在每个单元格中打印每个条目,请尝试以下解决方案,

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    user = coreDataHandler.getSortedData()

    return user!.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")

    let currentUser  = user[indexPath.row]

    cell?.textLabel?.text = String(describing: currentUser.username)

    return cell!
}

注意:这只是一个伪可能包含错误


0
投票

你做错了

这样做

let user: [UserType] = []

override func viewDidLoad() {
    super.viewDidLoad()
    user = coreDataHandler.getSortedData()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return user.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
    let currentUser = user[indexPath.row]
    cell?.textLabel?.text = "\(currentUser.username)"
    return cell!
}

你不需要在cellForRowAt委托中再次迭代,因为它是自我迭代的delgate。

为了安全编码,请使用guard letif let来展开值。在任何时间强制解包导致应用程序崩溃。

© www.soinside.com 2019 - 2024. All rights reserved.