Objective-C: From Many to Many Relationships with CoreData

I have iPhone apps with two models, categories, and content that are many-to-many.

This is the code: Content

@interface Content : NSManagedObject { } @property(readwrite, retain) NSString *type; @property(readwrite, retain) NSString *mainText; ... @property (copy) NSSet * categories; @end 

Category

 @interface Category : NSManagedObject { } @property (nonatomic, retain) NSNumber * id; @property (nonatomic, retain) NSNumber * active; ... @property (copy) NSSet * contents; @end 

And then this operation:

 ... NSSet *tmp_set = [NSSet setWithArray:some_array_with_contents objectsAtIndexes:custom_indexes]]; cat.contents = tmp_set; [[DataModel managedObjectContext] save:&error]; ... 

On the last line, the application says poorly:

 -[__NSCFSet _isValidRelationshipDestination__]: unrecognized selector sent to instance 0x5c3bbc0 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFSet _isValidRelationshipDestination__]: unrecognized selector sent to instance 0x5c3bbc0' 
+4
source share
1 answer

Your relationship properties should not use a copy. They must be saved, for example:

 @property (nonatomic, retain) NSSet* categories; 

You do not want to copy the set of managed objects, because in the end you will get duplicate objects in the object graph. This will cause a big problem.

However, this is not a problem. The immediate problem is that something is causing a selector to send the managed entity to the collection itself.

Most likely, this is caused by the direct assignment of the copied set to the relationship directly, and not using one of the access methods defined in the .m file. The @dynamic directive will not create the setCategories method because it is a managed entity, so you do not receive proper KVO notifications, and the context is not updated properly. When it tries to save, it sends validation messages to the given object instead of the objects it contains.

You should have a method like addCategoryObjects: in the implementation file. Deleting a copy and using these methods should solve the problem.

+3
source

All Articles