Skip to content

Instantly share code, notes, and snippets.

@robfeldmann
Last active December 26, 2015 04:29
Show Gist options
  • Save robfeldmann/7093860 to your computer and use it in GitHub Desktop.
Save robfeldmann/7093860 to your computer and use it in GitHub Desktop.
A class that encapsulates setting up a Core Data stack, separating this function from the rest of a Cocoa application, particularly from the Application Delegate. This was inspired/copied from NSScreencast.com episode 11.
//
// PJSDatModel.h
// PJSBoilerplate
//
// Created by Rob Feldmann on 8/8/13.
// Copyright (c) 2013 PajamaSoft, LLC. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Inspiration: http://nsscreencast.com/episodes/11-core-data-basics
#import <Foundation/Foundation.h>
@interface PJSDataModel : NSObject
@property (nonatomic, readonly) NSManagedObjectContext *mainContext;
@property (nonatomic, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (nonatomic) BOOL supportsUndo; //Default = NO
#pragma mark - Class Methods
+ (instancetype)sharedDataModel;
#pragma mark - Instance Methods
- (NSString *)modelName;
- (NSString *)pathToModel;
- (NSString *)storeFilename;
- (NSString *)pathToLocalStore;
@end
//
// PJSDatModel.m
// PJSBoilerplate
//
// Created by Rob Feldmann on 8/8/13.
// Copyright (c) 2013 PajamaSoft, LLC. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Inspiration: http://nsscreencast.com/episodes/11-core-data-basics
#import "PJSDataModel.h"
@interface PJSDataModel ()
@property (nonatomic, strong) NSManagedObjectModel *managedObjectModel;
- (NSString *) documentsDirectory;
@end
@implementation PJSDataModel
@synthesize mainContext = _mainContext;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
#pragma mark - Class Methods
+ (instancetype)sharedDataModel {
static dispatch_once_t once;
static PJSDataModel *__instance;
dispatch_once(&once, ^{
__instance = [[PJSDataModel alloc] init];
__instance.supportsUndo = NO;
});
return __instance;
}
#pragma mark - Paths
- (NSString *)modelName {
return @"PJSDataModel";
}
- (NSString *)pathToModel {
return [[NSBundle mainBundle] pathForResource:[self modelName]
ofType:@"momd"];
}
- (NSString *)storeFilename {
return [[self modelName] stringByAppendingPathExtension:@"sqlite"];
}
- (NSString *)pathToLocalStore {
return [[self documentsDirectory] stringByAppendingPathComponent:[self storeFilename]];
}
- (NSString *)documentsDirectory {
static NSString *documentsDirectory = nil;
if (documentsDirectory == nil) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
}
return documentsDirectory;
}
#pragma mark - Accessors
- (NSManagedObjectContext *)mainContext {
if (_mainContext == nil) {
_mainContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
_mainContext.persistentStoreCoordinator = [self persistentStoreCoordinator];
}
return _mainContext;
}
- (NSManagedObjectModel *)managedObjectModel {
if (_managedObjectModel == nil) {
NSURL *storeURL = [NSURL fileURLWithPath:[self pathToModel]];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:storeURL];
}
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (_persistentStoreCoordinator == nil) {
DDLogCVerbose(@"SQLITE STORE PATH: %@", [self pathToLocalStore]);
NSURL *storeURL = [NSURL fileURLWithPath:[self pathToLocalStore]];
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:[self managedObjectModel]];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
NSError *e = nil;
if (![psc addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeURL
options:options
error:&e]) {
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:e forKey:NSUnderlyingErrorKey];
NSString *reason = @"Could not create persistent store.";
NSException *exc = [NSException exceptionWithName:NSInternalInconsistencyException
reason:reason
userInfo:userInfo];
@throw exc;
}
_persistentStoreCoordinator = psc;
}
return _persistentStoreCoordinator;
}
- (void)setSupportsUndo:(BOOL)supportsUndo {
if (supportsUndo) {
self.mainContext.undoManager = [[NSUndoManager alloc] init];
} else {
self.mainContext.undoManager = nil;
}
}
@end
//
// PJSDatModelTests.m
// PJSBoilerplate
//
// Created by Rob Feldmann on 9/22/13.
// Copyright (c) 2013 PajamaSoft, LLC. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#import <XCTest/XCTest.h>
#import "PJSDataModel.h"
@interface PJSDatModelTests : XCTestCase
@property (nonatomic, strong) PJSDataModel *dataModel;
@end
@implementation PJSDatModelTests
- (void)setUp
{
[super setUp];
self.dataModel = [PJSDataModel sharedDataModel];
}
- (void)tearDown
{
// Put teardown code here; it will be run once, after the last test case.
[super tearDown];
}
-(void)testDataModelInstantiation {
XCTAssertNotNil(self.dataModel, @"dataModel should not be nil");
}
-(void)testSingletonBehavior {
PJSDataModel *one = [PJSDataModel sharedDataModel];
PJSDataModel *two = [PJSDataModel sharedDataModel];
XCTAssertEqualObjects(one, two, @"singleton instances should be equal");
}
-(void)testPaths {
XCTAssertNotNil(self.dataModel.pathToModel, @"pathToModel should not be nil");
XCTAssertNotNil(self.dataModel.storeFilename, @"storeFilename shold not be nil");
XCTAssertNotNil(self.dataModel.pathToLocalStore, @"pathToLocalStore should not be nil");
}
-(void)testPersistentStoreCoordinatorProperty {
NSPersistentStoreCoordinator *psc = self.dataModel.persistentStoreCoordinator;
XCTAssertNotNil(psc, @"persistent store coordinator should not be nil");
}
-(void)testMainContextProperty {
NSManagedObjectContext *context = self.dataModel.mainContext;
XCTAssertNotNil(context, @"mainContext should not be nil");
XCTAssertTrue(context.concurrencyType == NSMainQueueConcurrencyType,
@"mainContext should be on the main thread");
XCTAssertEqual(context.persistentStoreCoordinator,
self.dataModel.persistentStoreCoordinator,
@"mainContext's persistentStoreCoordinator property should be equal to dataModel's psc");
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment