Permalink
Browse files

Initial commit.

  • Loading branch information...
0 parents commit 1a2f6ba0056e449058c18b224c8e8038cf41154e Simon Wolf committed Feb 22, 2011
@@ -0,0 +1,17 @@
+# Xcode
+build/*
+*.pbxuser
+!default.pbxuser
+*.mode1v3
+!default.mode1v3
+*.mode2v3
+!default.mode2v3
+*.perspectivev3
+!default.perspectivev3
+*.xcworkspace
+!default.xcworkspace
+xcuserdata
+profile
+*.moved-aside
+.DS_Store
+
@@ -0,0 +1,17 @@
+@interface AppDelegate : NSObject {
+ IBOutlet NSTextField *dataFormatTextField;
+ IBOutlet NSTableView *tableView;
+
+ NSPersistentStoreCoordinator *mPersistentStoreCoordinator;
+ NSManagedObjectModel *mManagedObjectModel;
+ NSManagedObjectContext *mManagedObjectContext;
+}
+
+@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
+@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
+@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
+
+- (IBAction)saveAction:sender;
+- (IBAction)createSampleData:(id)sender;
+
+@end
@@ -0,0 +1,246 @@
+#import "AppDelegate.h"
+
+#define kStoreType NSSQLiteStoreType
+//#define kStoreType NSXMLStoreType
+
+#define kStoreName @"MyDatabase"
+#define kStoreTypeXMLExtension @"xml"
+#define kStoreTypeSQLiteExtension @"sqlite"
+
+@interface AppDelegate()
+
+- (NSString *)applicationSupportFolder;
+- (void)migrateData;
+
+@end
+
+#pragma mark -
+
+@implementation AppDelegate
+
+- (id)init
+{
+ if (![super init]) return nil;
+
+ [self migrateData];
+ return self;
+}
+
+- (void)dealloc
+{
+ [mManagedObjectContext release], mManagedObjectContext = nil;
+ [mPersistentStoreCoordinator release], mPersistentStoreCoordinator = nil;
+ [mManagedObjectModel release], mManagedObjectModel = nil;
+
+ [super dealloc];
+}
+
+- (void)awakeFromNib
+{
+ if ([kStoreType isEqualToString:NSXMLStoreType]) {
+ [dataFormatTextField setStringValue:@"XML"];
+ } else {
+ [dataFormatTextField setStringValue:@"SQLite"];
+ }
+}
+
+
+#pragma mark -
+#pragma mark Property Override Methods
+
+- (NSManagedObjectModel *)managedObjectModel
+{
+ if (mManagedObjectModel) return mManagedObjectModel;
+
+ mManagedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];
+ return mManagedObjectModel;
+}
+
+- (NSPersistentStoreCoordinator*)persistentStoreCoordinator
+{
+ if (mPersistentStoreCoordinator) return mPersistentStoreCoordinator;
+
+ NSError *error = nil;
+ NSManagedObjectModel *mom = [self managedObjectModel];
+ if (!mom) {
+ NSAssert(NO, @"NSManagedObjectModel is nil");
+ NSLog(@"%@:%s No model to generate a store from", [self class], _cmd);
+ return nil;
+ }
+
+ NSFileManager *fileManager = [NSFileManager defaultManager];
+ NSString *applicationSupportFolder = [self applicationSupportFolder];
+ if ( ![fileManager fileExistsAtPath:applicationSupportFolder isDirectory:NULL] ) {
+ if (![fileManager createDirectoryAtPath:applicationSupportFolder withIntermediateDirectories:YES attributes:nil error:nil]) {
+ NSAssert(NO, ([NSString stringWithFormat:@"Failed to create App Support directory %@", applicationSupportFolder]));
+ NSLog(@"Failed to create application directory: %@", applicationSupportFolder);
+ return nil;
+ }
+ }
+
+ NSString *filePath = [applicationSupportFolder stringByAppendingPathComponent:kStoreName];
+ if ([kStoreType isEqualToString:NSXMLStoreType]) {
+ filePath = [filePath stringByAppendingPathExtension:kStoreTypeXMLExtension];
+ } else {
+ filePath = [filePath stringByAppendingPathExtension:kStoreTypeSQLiteExtension];
+ }
+ NSURL *url = [NSURL fileURLWithPath:filePath];
+ mPersistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
+ NSDictionary *optionsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, nil];
+ if (![mPersistentStoreCoordinator addPersistentStoreWithType:kStoreType configuration:nil URL:url options:optionsDictionary error:&error]) {
+ [[NSApplication sharedApplication] presentError:error];
+ [mPersistentStoreCoordinator release], mPersistentStoreCoordinator = nil;
+ return nil;
+ }
+
+ return mPersistentStoreCoordinator;
+}
+
+- (NSManagedObjectContext *) managedObjectContext
+{
+ if (mManagedObjectContext) return mManagedObjectContext;
+
+ NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
+ if (!coordinator) {
+ NSMutableDictionary *dict = [NSMutableDictionary dictionary];
+ [dict setValue:@"Failed to initialize the store" forKey:NSLocalizedDescriptionKey];
+ [dict setValue:@"There was an error building up the data file. Please contact support." forKey:NSLocalizedFailureReasonErrorKey];
+ NSError *error = [NSError errorWithDomain:@"OtterSoftware" code:8001 userInfo:dict];
+ [[NSApplication sharedApplication] presentError:error];
+ return nil;
+ }
+ mManagedObjectContext = [[NSManagedObjectContext alloc] init];
+ [mManagedObjectContext setPersistentStoreCoordinator: coordinator];
+
+ return mManagedObjectContext;
+}
+
+
+#pragma mark -
+#pragma mark Public Action Methods
+
+- (IBAction) saveAction:(id)sender
+{
+ NSError *error = nil;
+
+ if (![[self managedObjectContext] commitEditing]) {
+ NSLog(@"%@:%s unable to commit editing before saving", [self class], _cmd);
+ }
+
+ if (![[self managedObjectContext] save:&error]) {
+ [[NSApplication sharedApplication] presentError:error];
+ }
+}
+
+- (IBAction)createSampleData:(id)sender
+{
+ NSEntityDescription *ed = [NSEntityDescription entityForName:@"OTSSampleDataItems" inManagedObjectContext:[self managedObjectContext]];
+
+ for (NSInteger index = 0; index < 5; index++) {
+ NSManagedObject *mo = [[NSManagedObject alloc] initWithEntity:ed insertIntoManagedObjectContext:[self managedObjectContext]];
+ [mo setValue:[NSString stringWithFormat:@"Item %d", index] forKey:@"itemName"];
+ [self saveAction:nil];
+ [mo release], mo = nil;
+ }
+
+ [tableView reloadData];
+}
+
+
+#pragma mark -
+#pragma mark Private Methods
+
+- (NSString *)applicationSupportFolder
+{
+ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
+ NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory();
+ return [basePath stringByAppendingPathComponent:@"OTSCoreDataFormatSwitcher"];
+}
+
+- (void)migrateData
+{
+ NSString *applicationSupportFolder = [self applicationSupportFolder];
+ if (![[NSFileManager defaultManager] fileExistsAtPath:applicationSupportFolder isDirectory:NULL])
+ return;
+
+ NSString *oldFormatFilePath = [applicationSupportFolder stringByAppendingPathComponent:kStoreName];
+ NSString *newFormatFilePath = oldFormatFilePath;
+ NSString *archiveFileName = oldFormatFilePath;
+
+ if ([kStoreType isEqualToString:NSXMLStoreType]) {
+ oldFormatFilePath = [oldFormatFilePath stringByAppendingPathExtension:kStoreTypeSQLiteExtension];
+ newFormatFilePath = [newFormatFilePath stringByAppendingPathExtension:kStoreTypeXMLExtension];
+ archiveFileName = [[archiveFileName stringByAppendingString:@" - Archive"] stringByAppendingPathExtension:kStoreTypeSQLiteExtension];
+ } else {
+ oldFormatFilePath = [oldFormatFilePath stringByAppendingPathExtension:kStoreTypeXMLExtension];
+ newFormatFilePath = [newFormatFilePath stringByAppendingPathExtension:kStoreTypeSQLiteExtension];
+ archiveFileName = [[archiveFileName stringByAppendingString:@" - Archive"] stringByAppendingPathExtension:kStoreTypeXMLExtension];
+ }
+
+ if (![[NSFileManager defaultManager] fileExistsAtPath:oldFormatFilePath])
+ return;
+
+ NSError *error = nil;
+ if ([[NSFileManager defaultManager] fileExistsAtPath:newFormatFilePath]) {
+ if (![[NSFileManager defaultManager] removeItemAtPath:newFormatFilePath error:&error]) {
+ NSLog(@"Failed to delete the pre-existing file %@: %@", newFormatFilePath, error);
+ return;
+ }
+ }
+
+ NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
+ NSPersistentStore *ps = nil;
+ if ([kStoreType isEqualToString:NSXMLStoreType]) {
+ ps = [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:oldFormatFilePath] options:nil error:&error];
+ } else {
+ ps = [psc addPersistentStoreWithType:NSXMLStoreType configuration:nil URL:[NSURL fileURLWithPath:oldFormatFilePath] options:nil error:&error];
+ }
+ [psc migratePersistentStore:ps toURL:[NSURL fileURLWithPath:newFormatFilePath] options:nil withType:kStoreType error:&error];
+ [psc release], psc = nil;
+
+ // Archive the old format file
+ if ([[NSFileManager defaultManager] fileExistsAtPath:archiveFileName isDirectory:nil])
+ [[NSFileManager defaultManager] removeItemAtPath:archiveFileName error:nil];
+ [[NSFileManager defaultManager] moveItemAtPath:oldFormatFilePath toPath:archiveFileName error:nil];
+}
+
+
+#pragma mark -
+#pragma mark NSApplicationDelegate Methods
+
+- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
+{
+ if (!mManagedObjectContext) return NSTerminateNow;
+
+ if (![mManagedObjectContext commitEditing]) {
+ NSLog(@"%@:%s unable to commit editing to terminate", [self class], _cmd);
+ return NSTerminateCancel;
+ }
+
+ if (![mManagedObjectContext hasChanges]) return NSTerminateNow;
+
+ NSError *error = nil;
+ if (![mManagedObjectContext save:&error]) {
+ BOOL result = [sender presentError:error];
+ if (result) return NSTerminateCancel;
+
+ NSString *question = NSLocalizedString(@"Could not save changes while quitting. Quit anyway?", @"Quit without saves error question message");
+ NSString *info = NSLocalizedString(@"Quitting now will lose any changes you have made since the last successful save", @"Quit without saves error question info");
+ NSString *quitButton = NSLocalizedString(@"Quit anyway", @"Quit anyway button title");
+ NSString *cancelButton = NSLocalizedString(@"Cancel", @"Cancel button title");
+ NSAlert *alert = [[NSAlert alloc] init];
+ [alert setMessageText:question];
+ [alert setInformativeText:info];
+ [alert addButtonWithTitle:quitButton];
+ [alert addButtonWithTitle:cancelButton];
+
+ int answer = [alert runModal];
+ [alert release], alert = nil;
+ if (answer == NSAlertAlternateReturn) return NSTerminateCancel;
+
+ }
+
+ return NSTerminateNow;
+}
+
+@end
Binary file not shown.
Binary file not shown.
Binary file not shown.
Oops, something went wrong.

0 comments on commit 1a2f6ba

Please sign in to comment.