一对多关系核心数据获取数据

问题描述 投票:0回答:1

关于这个主题有很多问题,但我无法让它发挥作用。

在这个vadian的答案中,他通过两个重复的循环得到了价值:

  1. swift 3 - core data relationship - fetch data
  2. https://stackoverflow.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)

如果我在我的例子中有多个爱好,是否有可能获得所有与location = stadium的爱好,例如使用第二个谓词参数,而不是寻找具有for循环的person1的person = stadium的这些爱好?

swift core-data one-to-many
1个回答
1
投票

toHobbies属性是NS的Any,所以你需要在循环中对它或每个x进行类型转换。

对于谓词,您可以使用“toHobbies.location =%@”之类的键路径

© www.soinside.com 2019 - 2024. All rights reserved.