【发布时间】:2015-05-29 21:08:08
【问题描述】:
我在 tableView1 中有一个 Person 类,然后在 TableView2 中,用户添加品牌以与该人关联。我的获取请求试图取回他们选择的人并使用该人的相关品牌填充 tableView 的行,但我被困在这里:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.CellReuseIdentifier, forIndexPath: indexPath) as! UITableViewCell
let brandSetAllObjects = brandSet?.allObjects
let brand = brandSetAllObjects as? Brand[indexPath.row]
cell.textLabel!.text = brand.valueForKey("name") as? String
return cell
}
获取:
//Helper Function to Fetch Core Data
func fetchCoreData() {
//1
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
//2
let fetchRequest = NSFetchRequest(entityName:"Person")
//3
var error: NSError?
let fetchedResults =
managedContext.executeFetchRequest(fetchRequest,
error: &error) as? [NSManagedObject]
if let results = fetchedResults as? [Person] {
for selectedPerson in results {
brandSet = selectedPerson.brands
println(brandSet)
}
} else {
println("Could not fetch \(error), \(error!.userInfo)")
}
类:
import Foundation
import CoreData
class Brand: NSManagedObject {
@NSManaged var name: String
@NSManaged var people: NSSet
}
import Foundation
import CoreData
class Person: NSManagedObject {
@NSManaged var name: String
@NSManaged var brands: NSSet
func addBrandsObject(value: Brand) {
self.mutableSetValueForKey("brands").addObject(value)
}
}
【问题讨论】:
-
这行代码让我有点困惑,你能详细说明一下吗 -
let brand = brandSetAllObjects as? Brand[indexPath.row]? -
有人在较早的答案中建议通过 .allObjects 将 NSSet 放入一个数组中......所以我试图将该数组转换为(不成功)我可以用来填充我的 tableView 的东西跨度>
标签: ios uitableview swift core-data