更新は、新しいものを作成するのと同じくらい簡単です。
特定のオブジェクトを更新するには、NSFetchRequest
. このクラスは、SQL 言語の SELECT ステートメントに相当します。
簡単な例を次に示します。
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Favorits" inManagedObjectContext:moc]];
NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];
// error handling code
配列results
には、sqlite ファイル内に含まれるすべての管理対象オブジェクトが含まれます。特定のオブジェクト (または複数のオブジェクト) を取得する場合は、その要求で述語を使用する必要があります。例えば:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title == %@", @"Some Title"];
[request setPredicate:predicate];
この場合results
、 title が と等しいオブジェクトが含まれますSome Title
。述語を設定することは、SQL ステートメントに WHERE 句を入れることと同じです。
詳細については、Core Data プログラミング ガイドとNSFecthRequest
クラス リファレンスを読むことをお勧めします。
それが役に立てば幸い。
EDIT (更新に使用できるスニペット)
// maybe some check before, to be sure results is not empty
Favorits* favoritsGrabbed = [results objectAtIndex:0];
favoritsGrabbed.title = @"My Title";
// save here the context
NSManagedObject
またはサブクラスを使用していない場合。
// maybe some check before, to be sure results is not empty
NSManagedObject* favoritsGrabbed = [results objectAtIndex:0];
[favoritsGrabbed setValue:@"My title" forKey:@"title"];
// save here the context
どちらの場合もsave
、コンテキストで a を実行すると、データが更新されます。