Reputation: 4343
When you create a managed object relationship (i.e. one to many), and then you create a NSManagedObject subclass, you would code that relationship like:
@NSManaged var dogs: NSSet
But I found out that instead you can write:
@NSManaged var dogs: Set<Dog>
Which in my opinion, it is much more convenient because you have a typed Set and casting in Swift is quite verbose.
Edited:
Actually, I have found out that you can use the insert
and remove
method of the Set so it's even easier.
I know about Swift automatic bridging from some Foundation classes to Swift classes (i.e. NSArray
to Array
and NSSet
to Set
).
But I haven't found about using Swift typed Sets for implementing Core Data Managed object subclasses in the docs or in any other tutorial and I wonder why.
I'm using Xcode 7.2 and Swift 2 and it works fine in my project. Does it also work for someone else? some Apple doc somewhere? or is it a bad idea for some reason I'm missing?
Upvotes: 4
Views: 864
Reputation: 80273
Yes, this is common practice among many developers as far as I know.
In fact, the generated NSManagedObject
subclasses are not at all perfect when it comes to the generated types. For examples, primitives still have problems, and NSNumber
sometimes bridges successfully to Bool
, sometimes not. Quite often I had to modify the optional state as well.
If you leave the preset NSSet
, you can still cast to Set<Type>
which is what I did before getting into the habit of changing the generated subclasses' to-many properties to typed sets.
Upvotes: 3