CoreDataオブジェクトをプログラムで更新するにはどうすればよいのでしょうか。ただし、オブジェクトはNSSetです。だから私はこれを以下のスキームで要約することができます:
Property
---------
name
price
typology
Property_has_typology
---------------------
typology_id
property
プロパティとProperty_has_typologyの間には1対多の関係があります。1つのプロパティには、Bed&Breakfast、Villa、Hotel、Mansion、Country Houseなどのいくつかの類型(別名カテゴリ)がある場合があります。
そこで、ユーザーにTableViewで複数の行を選択させ、[保存]をクリックしたときにこれらの変更を保存します。私もです:
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];
}
これはちょっと機能しますが、問題は、既存の値を実際には更新しないことです。それはそれを上書きするだけです。したがって、同じ2つのアイテムを2回保存すると(例として)、データベースに次のようになります。
PK TYPOLOGY
------------
1 |
2 |
3 | 4
4 | 6
つまり、それらは保存されていますが、空の行も作成されます(削除/更新する代わりにそれらをクリアします)。
どんな助けでもいただければ幸いです。ありがとう!