gpt4 book ai didi

ios - 如何在 Swift 中从核心数据中获取 NSSet

转载 作者:可可西里 更新时间:2023-11-01 01:05:53 25 4
gpt4 key购买 nike

我有一个 Person 类和一个 Brand 类,它们是 Core Data 中的关系。我知道如何获取整个 Person 类 (NSManagedObject),但我如何深入了解以仅获取与此人关联的品牌?

    import Foundation
import CoreData

class Person: NSManagedObject {

@NSManaged var name: String
@NSManaged var brands: NSSet

func addBrandsObject(value: Brand) {
self.mutableSetValueForKey("brands").addObject(value)
}

}

import Foundation
import CoreData

class Brand: NSManagedObject {

@NSManaged var name: String
@NSManaged var people: NSSet


}

View Controller :

![import UIKit
import CoreData

class BrandsTableTableViewController: UITableViewController {


var brands = \[NSManagedObject\]()
var selectedPerson: Person?
var selectedBrand: Brand?

//Fetch Core Data
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.fetchCoreData()
}

//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 {
////what here?
} else {
println("Could not fetch \(error), \(error!.userInfo)")
}
}][1]

enter image description here enter image description here

最佳答案

因为你已经有了 person 实例,只需访问关系:

    for person in results {
let brandSet = person.brands
}

无需提取。

这当然假设您从 PersonBrand 的关系称为 brands

还会有一些转换,没有转换就不能快速......

关于ios - 如何在 Swift 中从核心数据中获取 NSSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30494680/

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