2016-05-17 58 views
0

我的iOS應用程序嵌入一個.sqlite數據庫,其中包含具有郵政編碼和地理位置信息的城市列表。核心數據:使用捆綁的數據庫初始化persisent商店

我初始化我的核心數據堆棧是這樣的:

- (void)initializeCoreData { 
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"cities" withExtension:@"momd"]; 
NSManagedObjectModel *mom = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; 
NSAssert(mom != nil, @"Error initializing Managed Object Model"); 

NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom]; 
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType]; 
[moc setPersistentStoreCoordinator:psc]; 
[self setManagedObjectContext:moc]; 
NSURL *storeURL = [[NSBundle mainBundle] URLForResource:@"cities" withExtension:@"sqlite"]; 

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) { 
    NSError *error = nil; 
    NSPersistentStoreCoordinator *psc = [[self managedObjectContext] persistentStoreCoordinator]; 
    NSDictionary * options = @{NSSQLitePragmasOption:@{@"journal_mode":@"DELETE"}}; 
    NSPersistentStore *store = [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]; 
    NSAssert(store != nil, @"Error initializing PSC: %@\n%@", [error localizedDescription], [error userInfo]); 
}); 

}

正如你所看到的,我不要複製數據庫的應用程序目錄,而是直接從應用程序包閱讀。

我只需要讀取這個數據庫,那麼像我這樣初始化Core Data是安全的,還是應該在將數據庫複製到應用程序目錄之前?

回答

0

是的,它是安全的,但我想補充的「只讀」選項,以及這樣就可以保護自己免受潛在的錯誤:

NSMutableDictionary *options = [NSMutableDictionary dictionary]; 
options[NSReadOnlyPersistentStoreOption] = @YES; 
options[NSSQLitePragmasOption] = @{@"journal_mode":@"DELETE"};