Reputation: 276
I have an entity which looks like this:
Entityname = Country
with the attributes "city" and "person".
Country *country = [NSEntityDescription insertNewObjectForEntityForName:@"Country" inManagedObjectContext:context];
country.city = @"New York";
country.person = @"Doug";
country.person = @"Carry";
country.person = @"Arthur";
I want to save more then one people in that City.
I am using the code posted above, but only the last person is saved.
How I can save more then one people in CoreData?
Hope you can help me.
Upvotes: 1
Views: 728
Reputation: 8501
Try this code. Hope this will help you
yourArray = [[NSMutableArray alloc]initWIthObjects:@"Doug",@"Carry",@"Arthur"];
for(int i = 0; i < [yourArray count]; i++)
{
NSManagedObjectContext *context = [self managedObjectContext];
countryObject=[NSEntityDescription
insertNewObjectForEntityForName:@"Country"
inManagedObjectContext:context];
countryObject.city = @"New york";
countryObject.people = [NSString stringWithFormat:@"%@",[yourArray objectAtIndex:i]];
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}
UPDATE:
AFTER YOU EXPLAINED THAT YOU DONT NEED THREE DIFFERENT INSTANCES, then
This can be done by creating a separate entity for City
and People
, then make a relationship between them as to-many relationship.
So that you can achieve like that.
Upvotes: -1
Reputation: 35636
An approach for solving your problem would be:
...
- (void)addPersonObject:(Person *)value;
- (void)removePersonObject:(Person *)value;
- (void)addPersons:(NSSet *)value;
- (void)removePersons:(NSSet *)value;
...
From this point is quite obvious to figure out how to add multiple objects :) I know that all this may seem hard at first but once you get yourself into this you will really be able to manage complex object graphs easy and efficiently. I hope that this information will set you on the right track!
Upvotes: 2
Reputation: 259
You will need to create an array with all the people you need to save to the core data model.
Upvotes: 0