Get all attributes of an entity to a label in row in tableview with core data swift ios

痴心易碎 提交于 2019-12-11 14:33:20

问题


I have defined the two attribues Name and description to an entity named Forms and I want retrieve the name in first label and desc in 2nd label in a row of a tableview

what I have made

what I cuurently retrieve

I want these all values to be printed in every cell instead of sigle cell repeated every time

        let context = appDel.persistentContainer.viewContext
let results = try! context.fetch(request)

for result in results as! [NSManagedObject] {

    let formNameIs = result.value(forKey: "formName") as? String
    let formDescIs = result.value(forKey: "formDesc") as? String

cell.titleLabel.text = formNameIs!
cell.descLabel.text = formDescIs
    print(formNameIs!, formDescIs!)

}

回答1:


It looks like you have misunderstood how tableViews work. You do not need to iterate through all the objects; you should locate the correct object for the row (as indicated in the indexPath argument), and set the labels using the attribute values from that object.

So, make the results array a property of your view controller:

var results : [NSManagedObject] = []

In viewDidLoad, populate your results array from CoreData:

...
// presumably you have code to define the fetch request
let context = appDel.persistentContainer.viewContext
results = try! context.fetch(request)

In the tableView's numberOfRowsInSection method, return the count of objects in results

return results.count

And in the tableView's cellForRowAt: method, locate the correct object from the results array, using the indexPath argument:

let result = results[indexPath.row]
let formNameIs = result.value(forKey: "formName") as? String
let formDescIs = result.value(forKey: "formDesc") as? String
cell.titleLabel.text = formNameIs!
cell.descLabel.text = formDescIs
print(formNameIs!, formDescIs!)


来源:https://stackoverflow.com/questions/47854988/get-all-attributes-of-an-entity-to-a-label-in-row-in-tableview-with-core-data-sw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!