CoreData Objective-C saveContext fetch してみた

#Core Data

## Overview 

CoreData の保存と取得を簡易的にやってみました。

なんだかマイグレーションも楽になったみたいで、良い感じでした。


## Insert

```Objective-C
NSManagedObject* user = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:self.persistentContainer.viewContext];
    
    [user setValue:@"keisukeYamagishi" forKey:@"name"];
    [user setValue:@"1234567890" forKey:@"age"];
    
    NSManagedObject* person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.persistentContainer.viewContext];
    
    [person setValue:@"人間ですから" forKey:@"name"];
    [person setValue:@"でかいぜ" forKey:@"height"];
    
    [self saveContext];

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"CoreDAta"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    // Replace this implementation with code to handle the error appropriately.
                    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                    
                    /*
                     Typical reasons for an error here include:
                     * The parent directory does not exist, cannot be created, or disallows writing.
                     * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                     * The device is out of space.
                     * The store could not be migrated to the current model version.
                     Check the error message to determine what the actual problem was.
                    */
                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }
    
    return _persistentContainer;
}


- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}

```

これで保存できます。

## Select

```Objective-C 
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
    
    NSManagedObjectContext* context = appDelegate.persistentContainer.viewContext;
    
    NSFetchRequest* fetch = [NSFetchRequest new];
    
    NSEntityDescription* userEntity = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context];
    
    [fetch setEntity:userEntity];
    
    NSArray* objects = [context executeFetchRequest:fetch error:nil];
    
    NSLog(@"Request: \n%@",objects);
    
    
    NSEntityMapping* personEntitiy = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context];
    
    [fetch setEntity:personEntitiy];
    
    NSArray* persons = [context executeFetchRequest:fetch error:nil];
    
    NSLog(@"persons: %@",persons);
    
```

これで出せます。


##マイグレーション

マイグレーションはなんだか、追加すれば良いだけのようですね。

アップデート楽だし、これの方が良いかも知れんですね。