Last active
October 23, 2016 15:59
-
-
Save dmitryshliugaev/39a0c6df8781aa71101d to your computer and use it in GitHub Desktop.
CoreData Service for RestKit Manager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "CoreDataManager.h" | |
#import <RestKit/RestKit.h> | |
#import "IGDebug.h" | |
@implementation CoreDataManager | |
@synthesize managedObjectContext = _managedObjectContext; | |
@synthesize managedObjectModel = _managedObjectModel; | |
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator; | |
+ (CoreDataManager*)sharedManager | |
{ | |
static CoreDataManager* instance; | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, ^{ | |
instance = [[CoreDataManager alloc] init]; | |
}); | |
return instance; | |
} | |
+ (void)saveContext | |
{ | |
[[self sharedManager] saveContext]; | |
} | |
- (void)saveContext | |
{ | |
NSError *error = nil; | |
NSManagedObjectContext *managedObjectContext = self.managedObjectContext; | |
if (managedObjectContext != nil) { | |
if ([managedObjectContext hasChanges]) | |
{ | |
if (![managedObjectContext saveToPersistentStore:&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. | |
IGLog(@"Unresolved error %@, %@", error, [error userInfo]); | |
abort(); | |
} | |
} | |
} | |
} | |
#pragma mark - Core Data stack | |
// Returns the managed object context for the application. | |
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application. | |
- (NSManagedObjectContext *)managedObjectContext | |
{ | |
return [RKManagedObjectStore defaultStore].mainQueueManagedObjectContext; | |
} | |
// Returns the managed object model for the application. | |
// If the model doesn't already exist, it is created from the application's model. | |
- (NSManagedObjectModel *)managedObjectModel | |
{ | |
if (_managedObjectModel != nil) { | |
return _managedObjectModel; | |
} | |
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"]; | |
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; | |
return _managedObjectModel; | |
} | |
// Returns the persistent store coordinator for the application. | |
// If the coordinator doesn't already exist, it is created and the application's store added to it. | |
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator | |
{ | |
if (_persistentStoreCoordinator != nil) { | |
return _persistentStoreCoordinator; | |
} | |
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Model.sqlite"]; | |
NSError *error = nil; | |
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; | |
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&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. | |
Typical reasons for an error here include: | |
* The persistent store is not accessible; | |
* The schema for the persistent store is incompatible with current managed object model. | |
Check the error message to determine what the actual problem was. | |
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory. | |
If you encounter schema incompatibility errors during development, you can reduce their frequency by: | |
* Simply deleting the existing store: | |
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil] | |
* Performing automatic lightweight migration by passing the following dictionary as the options parameter: | |
@{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES} | |
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details. | |
*/ | |
IGLog(@"Unresolved error %@, %@", error, [error userInfo]); | |
abort(); | |
} | |
return _persistentStoreCoordinator; | |
} | |
#pragma mark - Application's Documents directory | |
// Returns the URL to the application's Documents directory. | |
- (NSURL *)applicationDocumentsDirectory | |
{ | |
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; | |
} | |
// Fetch objects with a predicate | |
+(NSMutableArray *)searchObjectsForEntity:(NSString*)entityName withPredicate:(NSPredicate *)predicate andSortKey:(NSString*)sortKey andSortAscending:(BOOL)sortAscending | |
{ | |
NSManagedObjectContext* managedObjectContext = [CoreDataManager sharedManager].managedObjectContext; | |
// Create fetch request | |
NSFetchRequest *request = [[NSFetchRequest alloc] init]; | |
request.includesSubentities = NO; | |
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext]; | |
[request setEntity:entity]; | |
// If a predicate was specified then use it in the request | |
if (predicate != nil) | |
[request setPredicate:predicate]; | |
// If a sort key was passed then use it in the request | |
if (sortKey != nil) { | |
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:sortAscending]; | |
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; | |
[request setSortDescriptors:sortDescriptors]; | |
} | |
// Execute the fetch request | |
NSError *error = nil; | |
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; | |
// If the returned array was nil then there was an error | |
if (mutableFetchResults == nil) | |
IGLog(@"Couldn't get objects for entity %@", entityName); | |
// Return the results | |
return mutableFetchResults; | |
} | |
// Fetch objects without a predicate | |
+(NSMutableArray *)getObjectsForEntity:(NSString*)entityName withSortKey:(NSString*)sortKey andSortAscending:(BOOL)sortAscending | |
{ | |
return [self searchObjectsForEntity:entityName withPredicate:nil andSortKey:sortKey andSortAscending:sortAscending]; | |
} | |
+ (NSMutableArray*)getValuesOfField: (NSString*)field forEntity:(NSString *)entityName withSortKey:(NSString *)sortKey andSortAscending:(BOOL)sortAscending | |
{ | |
NSManagedObjectContext* managedObjectContext = [CoreDataManager sharedManager].managedObjectContext; | |
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:entityName]; | |
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext]; | |
// Required! Unless you set the resultType to NSDictionaryResultType, distinct can't work. | |
// All objects in the backing store are implicitly distinct, but two dictionaries can be duplicates. | |
// Since you only want distinct names, only ask for the 'name' property. | |
fetchRequest.resultType = NSDictionaryResultType; | |
fetchRequest.propertiesToFetch = [NSArray arrayWithObject:[[entity propertiesByName] objectForKey:field]]; | |
fetchRequest.returnsDistinctResults = YES; | |
// If a sort key was passed then use it in the request | |
if (sortKey != nil) | |
{ | |
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:sortAscending]; | |
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; | |
[fetchRequest setSortDescriptors:sortDescriptors]; | |
} | |
// Now it should yield an NSArray of distinct values in dictionaries. | |
return [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy]; | |
} | |
#pragma mark Count objects | |
// Get a count for an entity with a predicate | |
+(NSUInteger)countForEntity:(NSString *)entityName withPredicate:(NSPredicate *)predicate | |
{ | |
NSManagedObjectContext* managedObjectContext = [CoreDataManager sharedManager].managedObjectContext; | |
// Create fetch request | |
NSFetchRequest *request = [[NSFetchRequest alloc] init]; | |
request.includesSubentities = NO; | |
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext]; | |
[request setEntity:entity]; | |
[request setIncludesPropertyValues:NO]; | |
// If a predicate was specified then use it in the request | |
if (predicate != nil) | |
[request setPredicate:predicate]; | |
// Execute the count request | |
NSError *error = nil; | |
NSUInteger count = [managedObjectContext countForFetchRequest:request error:&error]; | |
// If the count returned NSNotFound there was an error | |
if (count == NSNotFound) | |
IGLog(@"Couldn't get count for entity %@", entityName); | |
// Return the results | |
return count; | |
} | |
// Get a count for an entity without a predicate | |
+(NSUInteger)countForEntity:(NSString *)entityName | |
{ | |
return [self countForEntity:entityName withPredicate:nil]; | |
} | |
+ (BOOL)deleteObjectsForEntity: (NSString*)entityName withPredicate: (NSPredicate *)predicate | |
{ | |
NSManagedObjectContext* managedObjectContext = [CoreDataManager sharedManager].managedObjectContext; | |
NSMutableArray* fetchedResults = [self searchObjectsForEntity:entityName withPredicate:predicate andSortKey:nil andSortAscending:YES]; | |
if (fetchedResults != nil) | |
{ | |
for (NSManagedObject* manObject in fetchedResults) | |
{ | |
[managedObjectContext deleteObject:manObject]; | |
} | |
return YES; | |
} | |
else | |
{ | |
return NO; | |
} | |
} | |
+ (void)deleteObject: (NSManagedObject*) object | |
{ | |
NSManagedObjectContext* managedObjectContext = [CoreDataManager sharedManager].managedObjectContext; | |
[managedObjectContext deleteObject:object]; | |
} | |
+ (void)deleteObjects: (NSArray*) objects | |
{ | |
for (NSManagedObject* obj in objects) | |
{ | |
[self deleteObject:obj]; | |
} | |
} | |
+ (void)clearAllData | |
{ | |
[[CoreDataManager sharedManager] clearAllData]; | |
} | |
- (void)clearAllData | |
{ | |
[[RKManagedObjectStore defaultStore] resetPersistentStores:nil]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment