Coredata数据库预填充未填充

时间:2014-04-14 10:00:39

标签: ios objective-c sqlite core-data

我试图从sqlite文件预填充coredata数据库,但我不明白数据库未填充的原因。我的sqlite文件正确地填充了我需要的所有数据,并添加到bundle ressources中。

这里是AppDelegate中的persistentStoreCoordinator方法:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (persistentStoreCoordinator != nil)
    {
        return persistentStoreCoordinator;
    }
    NSString    *storePath = [[self applicationDocumentsDirectory] stringByAppendingString:@"MyApp.db"];
    NSError     *error = nil;

    NSFileManager   *fm = [NSFileManager defaultManager];

    if (![fm fileExistsAtPath:storePath])
    {
        NSString    *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"MyApp" ofType:@"db"];

        if (defaultStorePath)
        {
            [fm copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
        }
    }

    NSURL           *storeUrl = [NSURL fileURLWithPath:storePath];
    NSDictionary    *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error])
    {
        NSLog(@"Unresolved error : %@: %@", error, [error userInfo]);
        abort();
    }

    return persistentStoreCoordinator;
}

在视图控制器中,我尝试获取条目,但似乎enter code here为空:

    NSManagedObjectContext  *managedObjectContext = [self managedObjectContext];
initWithEntityName:@"Type_textimage_4text"];
    NSFetchRequest          *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription     *description = [NSEntityDescription entityForName:@"Type_textimage_4text" inManagedObjectContext:managedObjectContext];

    [fetchRequest setEntity:description];


    NSMutableArray  *questions = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

    NSLog(@"question : %@", questions);

我可能错过了一些东西,但我找不到什么。有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

在回答上面的内容时,我正在添加一个App的AppDelegate.m文件,其中包含一个预先填充的sqlite数据库。为此,我在xcode上创建项目时选择了“使用核心数据”。虽然它对我有用,但我相信现在将NSDocument用于这种应用程序是一个更好的实践。其中一个优点是该项目已经处于与iCloud兼容的良好轨道上。我还没有这样做,所以我只是根据我读过/看过的内容发言。

//
//  AppDelegate.m
// 
//
//

#import "AppDelegate.h"
#import "MainView.h"


@implementation AppDelegate

@synthesize window = _window;

@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    UINavigationController *navViewController = (UINavigationController *)self.window.rootViewController;


        MainView *main=[[navViewController viewControllers]objectAtIndex:0];
        main.managedObjectContext=self.managedObjectContext;


    return YES;

}

- (void)applicationWillResignActive:(UIApplication *)application{
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{

}

- (void)applicationWillEnterForeground:(UIApplication *)application
{

}

- (void)applicationDidBecomeActive:(UIApplication *)application
{

}

- (void)applicationWillTerminate:(UIApplication *)application
{

}



- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {

            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } 
    }
}

#pragma mark - Core Data stack








- (NSManagedObjectContext *)managedObjectContext
{
    if (__managedObjectContext != nil) {
        return __managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        __managedObjectContext = [[NSManagedObjectContext alloc] init];
        [__managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return __managedObjectContext;
}






// 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:@"Solvents" withExtension:@"momd"];



    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return __managedObjectModel;
}



- (NSString *)applicationDocumentsDirectoryString {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}






- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil) {
        return __persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Solvents.sqlite"];

    NSString *storePath = [[self applicationDocumentsDirectoryString] stringByAppendingPathComponent: @"Solvents.sqlite"];


    //NSLog(@"store path %@", storePath);
    //NSLog(@"store URL%@", storeURL );



    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath:storePath ]) {



        NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"Solvents" ofType:@"sqlite"];


        if (defaultStorePath) {

            [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
        }
    }




    NSError *error = nil;
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {




        NSLog(@"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];
}




@end