我的iOS应用程序嵌入了一个.sqlite数据库,其中包含带有邮政编码和地理位置信息的城市列表。
我像这样初始化我的核心数据堆:
- (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 :(得分:0)
是的,这是安全的,但我会添加“只读”选项,以便您可以保护自己免受潜在的错误:
NSMutableDictionary *options = [NSMutableDictionary dictionary];
options[NSReadOnlyPersistentStoreOption] = @YES;
options[NSSQLitePragmasOption] = @{@"journal_mode":@"DELETE"};