gpt4 book ai didi

ios - 如何使用 NSSet 填充 tableView? ( swift )

转载 作者:搜寻专家 更新时间:2023-10-31 23:03:25 25 4
gpt4 key购买 nike

我在 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)
}

}

最佳答案

是否有特定的可排序顺序,您希望表格 View 的内容显示在其中?

除了直接访问数据结构“Brand”,您还可以拥有一个以统一方式操作数据的数据管理器。您可以将所有 Brand 信息保存在一个 NSSet 中,然后在您的数据管理器上有一个返回 NSArray 的方法(可能称为 brandArray).数据管理器可以获取 NSSet 的内容,将它们添加到数组中,然后对数组进行排序以使它们处于统一顺序并返回该数组。

UITableView 端,只需将 Brand[indexPath.row] 替换为 dataManager.brandArray[indexPath.row]

我对数据管理器的建议是制作一个将作为 singleton 实现的类. this tutorial 的第 4 步很好地解释了如何设置数据管理器。

旁注:数据管理器只是一个概念,不是严格的类或对象类型。它可以是管理数据的任何对象,尽管这通常作为可以从项目中的任何其他类访问的单例执行。

关于ios - 如何使用 NSSet 填充 tableView? ( swift ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30539101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com