Reputation: 1516
iOS beginner here.
Given an entity with a Many-to-Many relationship
@class Categories;
@interface Events : NSManagedObject
@property (nonatomic, retain) NSString * title;
@property (nonatomic, retain) NSSet *categories;
@end
@interface Events (CoreDataGeneratedAccessors)
- (void)addCategoriesObject:(Categories *)value;
- (void)removeCategoriesObject:(Categories *)value;
- (void)addCategories:(NSSet *)values;
- (void)removeCategories:(NSSet *)values;
@end
Which is related to
@interface Categories : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSManagedObject *events;
@end
And having some JSON data to populate the Events table
[{"title": "Test Exhibition", "categories": [{"name": "Exhibitions"}]}, {...}]
How should I format the JSON data to do something like
// Parse Events JSON
[events enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
...
Events *event = [NSEntityDescription
insertNewObjectForEntityForName:@"Events" inManagedObjectContext:context];
event.title = [obj objectForKey:@"title"];
NSSet *categories = [[[NSSet alloc] init] setByAddingObjectsFromArray:[obj objectForKey:@"categories"]];
NSLog(@"CATS %@", categories);
[event addCategories:categories];
to eventually get Core Data to find the relative Category (already added to the database) and attach it to the Event?
At the moment I get
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary entity]: unrecognized selector sent to instance 0x893a8c0'
Any help will be much appreciated, thanks!
Upvotes: 0
Views: 145
Reputation: 9006
categories
is an NSSet
of NSDictionaries
, but
- (void)addCategories:(NSSet *)values;
expects an NSSet
of NSManagedObject's
. So, you have to create an NSManagedObject
from each dictionary that describes a category, add them to a new NSSet
(or NSMutableSet
) and only then call addCategories:
with the new set.
Upvotes: 1