关于这个话题有很多问题,但我无法让它发挥作用。
在这个vadian的答案中,他通过两个重复循环得到了价值:
它对我的代码不起作用,我无法弄清楚原因。
这是我的代码:
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的这些爱好?
答案 0 :(得分:1)
toHobbies属性是Any的NSSet,所以你需要在循环中对它或每个x进行类型转换。
对于谓词,您可以使用“toHobbies.location =%@”等关键路径