Search code examples
iphoneioscore-datansset

Fill NSSet with CoreData Objects


I have a One-To-Many Relationship in Core Data. Now I wanted to create a Object out of my Core Data Entity and set it to an NSSet. I think the Core Data Object is instantiate in the right way. But I didn't get it working to set my Object to an NSSet.

AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSSet *selectedCategories = [NSSet set];

for (NSString *categoryName in self.categories /*NSMutableArray propterty*/) {
    Category *category = [NSEntityDescription  
    insertNewObjectForEntityForName:@"Category" inManagedObjectContext:context];
    category.name = categoryName;
    [selectedCategories setByAddingObject:category];
}

[self.delegate addCategoryViewControllerDidSelectCategory:
                                 self didSelectCategories:selectedCategories];

I am still new to Core Data and iOS at all. I hope you can help me out folks. Thank you in advance.


Solution

  • This line

    [selectedCategories setByAddingObject:category];
    

    creates a new set that is not assigned to any variable. Try using a mutable set

    NSMutableSet *selectedCategories = [NSMutableSet set];
    
    for (NSString *categoryName in self.categories /*NSMutableArray propterty*/) {
        Category *category = [NSEntityDescription  
        insertNewObjectForEntityForName:@"Category" inManagedObjectContext:context];
        category.name = categoryName;
        [selectedCategories addObject:category];
    }