一对多关系核心数据获取数据
Posted
技术标签:
【中文标题】一对多关系核心数据获取数据【英文标题】:One to Many Relationship Core Data fetch Data 【发布时间】:2018-03-02 18:39:11 【问题描述】:关于这个主题有很多问题,但我无法解决。
在 vadian 的这个答案中,他通过两个重复循环获得了值:
-
swift 3 - core data relationship - fetch data
https://***.com/a/43846785/8887336
它不适用于我的代码,我不知道为什么。
这是我的代码:
import Foundation
import CoreData
struct HobbiesCollection
let typ: String
let location: String
class LoadData
class func load(context: NSManagedObjectContext)
let persons = ["Owen", "Greg"]
let futbal = HobbiesCollection(typ: "futbal", location: "stadium")
let swimming = HobbiesCollection(typ: "swimming", location: "pool")
let collection = [persons[0]: swimming, persons[1]: futbal]
for x in collection
let person = Person(context: context)
let hobbiesCD = Hobbies(context: context)
person.name = x.key
hobbiesCD.typ = x.value.typ
hobbiesCD.location = x.value.location
person.addToToHobbies(hobbiesCD)
do
try context.save()
catch let error
print(error.localizedDescription)
let fetch: NSFetchRequest<Person> = Person.fetchRequest()
var result = [Person]()
do
result = try context.fetch(fetch)
catch let error
print(error.localizedDescription)
for y in result
print("Persons:", y.name!)
for x in y.toHobbies!
let location = x.location Error: "Value of type 'Any' has no member 'location'"
我得到错误:
“任何”类型的值没有成员“位置”
我的两个核心数据类:
extension Person
@nonobjc public class func fetchRequest() -> NSFetchRequest<Person>
return NSFetchRequest<Person>(entityName: "Person")
@NSManaged public var name: String?
@NSManaged public var toHobbies: NSSet?
// MARK: Generated accessors for toHobbies
extension Person
@objc(addToHobbiesObject:)
@NSManaged public func addToToHobbies(_ value: Hobbies)
@objc(removeToHobbiesObject:)
@NSManaged public func removeFromToHobbies(_ value: Hobbies)
@objc(addToHobbies:)
@NSManaged public func addToToHobbies(_ values: NSSet)
@objc(removeToHobbies:)
@NSManaged public func removeFromToHobbies(_ values: NSSet)
extension Hobbies
@nonobjc public class func fetchRequest() -> NSFetchRequest<Hobbies>
return NSFetchRequest<Hobbies>(entityName: "Hobbies")
@NSManaged public var typ: String?
@NSManaged public var location: String?
@NSManaged public var toPerson: Person?
我还有一个关于谓词的问题。 如果我像这样进行谓词提取:
fetch.predicate = NSPredicate(格式: "name = %@", person1)
如果在我的示例中我有多个爱好,是否可以使用第二个谓词参数来获取所有具有位置 = 体育场的爱好,而不是使用 for 循环来查找具有位置 = person1 的体育场的这些爱好?
【问题讨论】:
【参考方案1】:toHobbies 属性是 Any 的 NSSet,因此您需要对它或循环中的每个 x 进行类型转换。
对于谓词,您可以使用诸如“toHobbies.location = %@”之类的键路径
【讨论】:
以上是关于一对多关系核心数据获取数据的主要内容,如果未能解决你的问题,请参考以下文章