daleijn
daleijn

Reputation: 738

Can't set relationship object to another object in CoreData

I have 2 Entities: Goal and Category. I added relationship "category" to Goal entity. I want that user can choose a category from list and then that category added as relation to Goal object. But I getting error: -[__NSSingleObjectSetI managedObjectContext]: unrecognized selector sent to instance 0x138a22fa0

My code:

- (BOOL)save {

    // Get Category object
    NSManagedObject *objCategory = [self getCategoryObjectWithID:@"1"];
    if (!objCategory) {
        NSLog(@"ERROR objCategory fetching!");
        return;
    }

 NSEntityDescription *entity =  [NSEntityDescription entityForName:@"Goal"
                                               inManagedObjectContext:[CoreDataWrapper myManagedContext]];

    NSManagedObject *goal = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:[CoreDataWrapper myManagedContext]];
    [goal setValue:strID forKey:@"id"];
    [goal setValue:[NSSet setWithObject:objCategory] forKey:@"category"]; // here error

return [CoreDataWrapper saveMyContext];

}

- (NSManagedObject *)getCategoryObjectWithID:(NSString *)catID {

    // Fetching
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Category"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %@", @"categoryID", catID];
    [fetchRequest setPredicate:predicate];

    // Execute Fetch Request
    NSError *fetchError = nil;
    NSArray *result = [[CoreDataWrapper myManagedContext] executeFetchRequest:fetchRequest error:&fetchError];

    if (!fetchError) {
        return result[0];
    }

    return nil;
}

I'm new to CoreData and maybe this some sort of dumb questions, but I followed many resourses and can't find what's a problem.

Upvotes: 3

Views: 699

Answers (1)

deadbeef
deadbeef

Reputation: 5563

If your Goal object can only have one category, then it's a to-one relationship, meaning that the category property is an object, not a set of objects (not even a set of 1 object).

You should set your category like so :

[goal setValue:objCategory forKey:@"category"];

Upvotes: 6

Related Questions