Reputation: 541
I have a User entity and a Hobby entity and a relationhip of to-many where one User can have many Hobbies. I am adding the user to a hobby like this, `@IBAction func addHobby(sender: AnyObject) {
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext
var newHobby = NSEntityDescription.insertNewObjectForEntityForName("Hobby", inManagedObjectContext: context) as! Hobby
newHobby.name = addHobbyTextField.text
newHobby.user = curUser
do{
try context.save()
} catch{
print("There was a problem \(error)")
}
}`
but I am trying to figure out how to loop through the User entity object to see what hobbies a certain user has. I am using this currently but its not working,
@IBAction func printUser(sender: AnyObject) {
print(curUser!.hobby! as NSSet)
}
I get this in the console:
Relationship 'hobby' fault on managed object (0x7fef13674e10) <Core_Data_Demo.Users: 0x7fef13674e10> (entity: Users; id: 0xd000000000040000 <x-coredata://5E62A797-4124-4816-8AC0-32C5E723F830/Users/p1> ; data: {
hobby = "<relationship fault: 0x7fef134515c0 'hobby'>";
password = test;
username = free;
})
Any help would be awesome, I'm stuck.
Upvotes: 0
Views: 1533
Reputation: 46728
The relationship will be a fault until you access it. That is what you are seeing in your print. You need to walk the relationship to see what is in it:
for item in curUser.hobby {
print(item)
}
That will cause the relationship to be accessed which will realize the relationship and give you a set of objects to walk.
Note that even with that each hobby will be a fault so you may want to touch a property on the hobby instead of printing the entire object:
for item in curUser.hobby {
print(item.name)
}
As an example.
I would suggest reading up on faulting in Core Data
Upvotes: 0