How to add element to NSOrderedSet for Core Data?

Another way of doing this is with the mutableOrderedSetValueForKey function in NSKeyValueCoding. You could say

owningObject.mutableOrderedSetValueForKey("items").addObject(anItem)

Unfortunately, this doesn't get you the compile-time checking of "items."


Swift:

let mutableItems = items.mutableCopy() as! NSMutableOrderedSet
mutableItems.addObject(anItem)
items = mutableItems.copy() as! NSOrderedSet

Objective-C:

NSMutableOrderedSet *mutableItems = (NSMutableOrderedSet *)items.mutableCopy;
[mutableItems addObject:anItem];
items = (NSOrderedSet *)mutableItems.copy;

The problem solved. There are two problems:

  1. Can't insert/add an existing item
  2. I have a stupid name conflict. So the suggestion in this post is good.

Thanks.