0

I need some help with my Swift rookie programming...

In a many-to-many relationship, I have a NSManagedObjectID that I`ve segued from another view controller.

To retrive data from it I have used this:

var elevid :NSManagedObjectID?

let person = context.object(with: studentId!)

nameTextField.text = person.value(forKey: "name") as? String

This works fine, but when I try to get an attribute from a relationship I`m stuck.

I´ve tried this:

let isAtSchool = person.value(forKeyPath: "isAtSchool.monday") as! Bool

but I get an error telling me:

Could not cast value of type '__NSSingleObjectSetI' (0x10ac63aa8) to 'NSNumber' (0x109e5a4a8).

If I use ? after as instead of ! it returns nil.

Someone know how to do this?

SimpleBeat
  • 747
  • 1
  • 10
  • 20
Petter
  • 1
  • 1
  • Can you describe the nature of the relationship and any relevant attributes? Especially, what exactly is `isAtSchool` and what is `monday` here? – Tom Harrington May 30 '17 at 19:10
  • Hi! isAtSchool is an entity with a many-to-many relationship. monday is an attribute from this entity. The managedObjectId is from a entity called "Students and is fetched with NSFetchedResultsController and segued from another viewController called "Pupils". Im trying to retrieve data and then update them, witch works fine when I use valueForKey, but not valueForKeyPath. Hope this clears up a little. Cheers – Petter May 30 '17 at 19:20

1 Answers1

0

When you ask for the name property you're asking for a single value, so that's no problem. But when you're using this key path you're traversing a to-many relationship. There could be 2 or 10 or a million related objects, but you you're asking for a single Bool. How is that supposed to work?

It's not clear what you actually want in this situation. Of those potentially millions of related objects, how do you want to calculate the value of that Bool? Probably you want to do something like pick out a single related object out of those (potential) millions and get the Bool from that single instance. But for all I know you might want to scan over all of them and see what the most common Bool value is.

How to change your code depends on what you really need, how that single Bool value should be determined. One way or another you need to get from (potential) millions of related objects to a single Bool-- and you can't do that via a key path lookup.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170
  • Hi! thanks for answering. How can I use NSmanagedObject ID and get a single property from a to-many relationship? or maybe I can't do that? sorry for being unclear here. Its the best I can do so far :) – Petter May 30 '17 at 19:36