I am wondering how I can programmatically update a Core Data object. The object is a NSSet though. So I can summarize this with the scheme below:
Property
---------
name
price
typology
Property_has_typology
---------------------
typology_id
property
There is a one-to-many relationship between the Property and Property_has_typology. As one property might have several typologies (aka categories) such as Bed & Breakfast, Villa, Hotel, Mansion, Country House.
So I let the user select multiple rows in my TableView and when he clicks save I want to store these changes. So I do:
NSMutableArray *storeItems = [[NSMutableArray alloc] init];
//Get selected items
for (int i = 0; i < [items count]; i++) {
Properties_has_typology *typo = [NSEntityDescription insertNewObjectForEntityForName:@"Properties_has_typology"
inManagedObjectContext: [PropertyProvider sharedPropertyProvider].context];
typo.typology_id = [NSNumber numberWithInt: (int)[items objectAtIndex:i]];
typo.property = property;
[storeItems addObject: typo];
}
//Store the items for the Property and save it
if ([storeItems count] > 0) {
NSLog(@"Going to save...");
NSSet *storeSet = [[NSSet alloc] initWithArray:storeItems];
property.typology = storeSet;
[property save];
[storeSet release];
}
This kinda works, the issue though is that it doesn’t really update the existing values. It just overrides it. So if I save the same two items twice (just as an example) I’d get the following in my database:
PK TYPOLOGY
------------
1 |
2 |
3 | 4
4 | 6
So yes they are being stored, but it also creates empty rows (clears them instead of deleting/updating them).
Any help would be appreciated. Thanks!
Apologies of there are any typos. I am on my windows machine at the moment so I cannot check it.