Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
NSOrderedSet does not work well on insert

Usually, we generate an entity class with Editor->Create NSManagedOBject Subclass... For example we created a subclass of NSManagedObject

Xcode generates the .h file like this:

@interface MyEntity : NSManagedObject

@property (nonatomic, retain) NSOrderedSet manySubs;

//... some methods generated by Xcode
- (void)addManySubsObject:(MySubEntity*)value;
//... some other methods generated by Xcode

@end

and the .m file like this:

@implement MyEntity

@dynamic manySubs;

@end

If you use MyEntity just like this, you will get an error when you try to insert a new MySubEntity class by calling [myEntityObj addManySubsObject:aSubEntityObj];.

The error reads:

Test[2002:707] *** -[NSSet intersectsSet:]: set argument is not an NSSet

This is a bug Apple hasn't resolved yet, but you can work around this bug by adding the following method to .m file.

- (void)addManySubsObject:(MySubEntity*)value{
    [self willChangeValueForKey:@"manySubs"];
    NSMutableOrderedSet *tempSet = [NSMutableOrderedSet orderedSetWithOrderedSet:self.manySubs];
    [tempSet addObject: value];
    self.manySubs = tempSet;
    [self didChangeValueForKey:@"manySubs"];
}

Be careful

Usually, we generate an entity class with Editor->Create NSManagedOBject Subclass... For example we created a subclass of NSManagedObject

Xcode generates the .h file like this:

@interface MyEntity : NSManagedObject

@property (nonatomic, retain) NSOrderedSet manySubs;

//... some methods generated by Xcode
- (void)addManySubsObject:(MySubEntity*)value;
//... some other methods generated by Xcode

@end

and the .m file like this:

@implement MyEntity

@dynamic manySubs;

@end

If you use MyEntity just like this, you will get an error when you try to insert a new MySubEntity class by calling [myEntityObj addManySubsObject:aSubEntityObj];.

The error reads:

Test[2002:707] *** -[NSSet intersectsSet:]: set argument is not an NSSet

This is a bug Apple hasn't resolved yet, but you can work around this bug by adding the following method to .m file.

- (void)addManySubsObject:(MySubEntity*)value{
    [self willChangeValueForKey:@"manySubs"];
    NSMutableOrderedSet *tempSet = [NSMutableOrderedSet orderedSetWithOrderedSet:self.manySubs];
    [tempSet addObject: value];
    self.manySubs = tempSet;
    [self didChangeValueForKey:@"manySubs"];
}

Be careful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.