简体   繁体   中英

How to fetch to-many relationships in Core data in IOS Swift?

I have been trying to fetch relationship values of to-many relationship in core data. I have to two entity Person and Address. Person can have multiple address and it has two attributes Name & age. While address just has one attribute City.

Here is how I'm trying to set the values

let managedContext = (UIApplication.sharedApplication().delegate as? AppDelegate)!.managedObjectContext

let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext)
let addEntity = NSEntityDescription.entityForName("Address", inManagedObjectContext: managedContext)

let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)

let address = NSManagedObject(entity: addEntity!, insertIntoManagedObjectContext: managedContext)

person.setValue(name, forKey: "name")
person.setValue(age, forKey: "age")
address.setValue(city, forKey: "city")

person.setValue(NSSet(object: address), forKey: "addresses")

do {
    try person.managedObjectContext?.save()
    people.append(person)
} catch let error as NSError {
    print("Could not save \(error)")
}

This is how my core data properties are set

extension Person {

   @NSManaged var age: NSNumber?
   @NSManaged var name: String?
   @NSManaged var addresses: Address?

}

extension Address {

   @NSManaged var city: String?
   @NSManaged var persons: Person?

}

Then to fetch the data in table view I'm trying to do something like this

let person = people[indexPath.row]
let address = person.mutableSetValueForKey("addresses")
print(address.allObjects.first as! Address)

Value of the print is something like this

<Address: 0x7f9481f1e290> (entity: Address; id: 0xd000000000040002 <x-coredata://7A4230B9-0EF0-44D5-BBDD-D8E9A3E38F59/Address/p1> ; data: <fault>)

Any help would be appreciated. Thanks in advance.

Check it is relationship (not attribute). And is to-many. Like this: 在此处输入图片说明 After that, it will like this:

extension Album {

    @NSManaged var createDate: NSDate?
    @NSManaged var isDefault: NSNumber?
    @NSManaged var name: String?
    @NSManaged var order: NSNumber?
    @NSManaged var picture: NSData?
    @NSManaged var notes: NSOrderedSet? // Attention: NSOrderedSet

}

The model you are showing is not what you state it to be. Your model shows a mis-named 1:1 relationship. Based on your code, you should bet getting a crash.

@NSManaged var addresses: Address?  // is not a 1:N

I recommend you review your data model and regenerate your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM