「iOS入門」Core Dataの使い方

コード:
1.contextを取得
– (NSManagedObjectContext *)managedObjectContext {
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:@selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
2.データを追加
NSManagedObjectContext *context = [self managedObjectContext];

// Create a new managed object
NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context];
[newDevice setValue:self.nameTextField.text forKey:@"name"];
[newDevice setValue:self.versionTextField.text forKey:@"version"];
[newDevice setValue:self.companyTextField.text forKey:@"company"];

NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(@"Can’t Save! %@ %@", error, [error localizedDescription]);
}

3.データを削除
NSManagedObjectContext *context = [self managedObjectContext];

// Delete object from database
[context deleteObject:[self.devices objectAtIndex:indexPath.row]];

NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Can’t Delete! %@ %@", error, [error localizedDescription]);
return;
}

4.データを修正
NSManagedObjectContext *context = [self managedObjectContext];

// Update existing device
[self.device setValue:self.nameTextField.text forKey:@"name"];
[self.device setValue:self.versionTextField.text forKey:@"version"];
[self.device setValue:self.companyTextField.text forKey:@"company"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(@"Can’t Save! %@ %@", error, [error localizedDescription]);
}
5. データを検索
// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Device"];
self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

詳細内容 http://www.appcoda.com/introduction-to-core-data/

IOS

Posted by arkgame