问题
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