Core Data – это объектноориентированная оболочка над базой данных приложения в iOS/Mac OS. Позволяет создавать таблицы визуально, сама следит за Commitment Control, управлением версиями и т.д.
Persistent Store – это “надежное” хранилище данных. (NSPersistenStoreCoordinator). Данные хранятся в applicationDocumentsDirectory/App.sqlite. Где App.sqlite – это база SQLite приложения.
Context – это instance базы. Промежуточное хранилище, в котором производятся изменения и затем утверждаются (Commitment). Также запрос производится из Context. У одной базы может быть много Context. В каждом Context есть Managed Objects.
Managed Object – объект, с которым мы работаем, но изменения, которые мы в него вносим не вносятся в Persistent Store до тех пор, пока мы не сделаем Save.
CoreData – Core Data Programming Guide
CoreDataSnippets – Core Data Code Snippets
Базовый запрос без предиката всех строк из таблицы:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
+ (BOOL)basicFetch { // Test Fetch of 1 item useDelegate NSManagedObjectContext *context = appDelegate.managedObjectContext; if (context == nil) { NSLog(@"Error: No context"); return NO; } NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"FLCatRanking" inManagedObjectContext:context]; [fetchRequest setEntity:entity]; NSError *error = nil; NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; if (fetchedObjects == nil) { // Handle the error NSLog(@"Error: No fetched objects."); return NO; } // Take first product name FLCatRanking *flCatRanking = [fetchedObjects objectAtIndex:0]; NSLog(@"First fetched item: %@", flCatRanking.prodID); return YES; } |
Запрос с фильтрацией – аналог WHERE в SQL :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
+ (NSMutableDictionary*) retrieveProductsForCategory: (NSString*) catName { NSMutableDictionary *dic = [[NSMutableDictionary alloc] init]; useDelegate NSManagedObjectContext *context = appDelegate.managedObjectContext; if (context == nil) { NSLog(@"Error: No context"); return nil; } NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"prodCatName == %@", catName]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"FLCatRanking" inManagedObjectContext:context]; [fetchRequest setEntity:entity]; [fetchRequest setPredicate:predicate]; NSError *error = nil; NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; if (fetchedObjects == nil) { // Handle the error NSLog(@"Error: No fetched objects."); return nil; } // Take first product name for (FLCatRanking *flCatRanking in fetchedObjects) { NSLog(@"FLCatRanking item: %@ - %@", flCatRanking.prodID, flCatRanking.prodPos); [dic addEntriesFromDictionary:[NSDictionary dictionaryWithObject:flCatRanking.prodID forKey:flCatRanking.prodPos]]; } return dic; } |