I have an entity called LogBook which has an attribute (called columns) for a set of LogBookColumn entities (one-to-many relationship).
The standard way I see to retrieve the mutable set of columns seems to be:
NSEntityDescription *myLogbook;
myLogbook = [NSEntityDescription insertNewObjectForEntityForName:@"LogBook"
inManagedObjectContext:self.managedObjectContext];
NSMutableSet *columns = [myLogbook mutableSetValueForKey:@"columns"];
Instead of method on the third line, I want to use dot notation. To do so, I have created class definitions, also called LogBook and LogBookColumn, and use @property to create the setters and getters.
LogBook *myLogBook;
myLogbook = [NSEntityDescription insertNewObjectForEntityForName:@"LogBook"
inManagedObjectContext:self.managedObjectContext];
NSMutableSet *columns = (NSMutableSet *)myLogbook.columns;
So, is columns truly a mutable set by default? I have done two things to verify:
- Attempted to write to the list, eg:
[columns addObject:aColumn]; - Asked with:
BOOL isKindOfMutableSet = [myLogbook.columns isKindOfClass:[NSMutableSet class]];
Both work with expected results, which may make this question overkill, but I am very concerned about memory errors that will be difficult to track down. I also wonder if asking the question isKindOfClass will work as I have defined this as a mutable set – so won’t it work even if the underlying memory organization doesn’t support mutable sets?
All of the above sums up to: is this the right way to access and change the columns property/attribute?
According to this documentation, to-many relationships should be declared as
NSSet, which makes sense. Even if the attribute returns anNSMutableSet, it is not guaranteed that updating theNSMutableSetwill properly update relationships (whichmutableSetValueForKey:does).If you really want a mutable accessor, then just create a
readonlyproperty that wrapsmutableSetValueForKey:Update:
Otherwise, we are supposed to use – (void)addLogBookColumnsObject:(LogBookColumn *)value;, – (void)removeLogBookColumnsObject:(LogBookColumn *)value;, – (void)addLogBookColumns:(NSSet *)values;, – (void)removeLogBookColumns:(NSSet *)values; that were generated by Core Data for us.