【发布时间】:2012-09-08 10:33:57
【问题描述】:
我正在创建一个 iPad 应用程序,它以 JSON 格式显示我从 API 获得的数据。我的核心数据模型有几个实体(国家、事件、会谈……)。对于每个实体,我都有一个 .json 文件,其中包含实体的所有实例及其属性以及关系。
我想在应用程序启动之前用这些实体填充我的 Core Data 数据模型(否则 iPad 需要大约 15 分钟才能使用工厂方法从多个 JSON 文件创建实体的所有实例)。
我目前正在像这样将数据导入 CoreData:
-(void)fetchDataIntoDocument:(UIManagedDocument *)document
{
dispatch_queue_t dataQ = dispatch_queue_create("Data import", NULL);
dispatch_async(dataQ, ^{
//Fetching data from application bundle
NSURL *countriesurl = [[NSBundle mainBundle] URLForResource:@"contries" withExtension:@"json"];
NSURL *eventsurl = [[NSBundle mainBundle] URLForResource:@"events" withExtension:@"json"];
//converting the JSON files to NSDictionaries
NSError *error = nil;
NSDictionary *countries = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:countriesurl] options:kNilOptions error:&error];
countries = [countries objectForKey:@"countries"];
NSDictionary *events = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:eventsurl] options:kNilOptions error:&error];
events = [events objectForKey:@"events"];
//creating entities using factory methods in NSManagedObject Subclasses (Country / Event)
[document.managedObjectContext performBlock:^{
NSLog(@"creating countries");
for (NSDictionary *country in countries) {
[Country countryWithCountryInfo:country inManagedObjectContext:document.managedObjectContext]; //creating Country entities
}
NSLog(@"creating events");
for (NSDictionary *event in events) {
[Event eventWithEventInfo:event inManagedObjectContext:document.managedObjectContext]; // creating Event entities
}
NSLog(@"done creating, saving document");
[document saveToURL:document.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:NULL];
}];
});
dispatch_release(dataQ);
}
这会将不同的 JSON 文件组合到一个 UIManagedDocument 中,然后我可以对其执行 fetchRequests 以填充 tableViews、mapView 等。
我正在寻找一种在我的应用程序之外创建此文档并将其添加到 mainBundle 的方法。然后我可以将它复制一次到应用程序 DocumentsDirectory 并能够使用它(而不是从原始 JSON 文件在应用程序中创建文档)。任何帮助表示赞赏!
【问题讨论】:
-
如果您将调用移至循环外的
-saveToURL:forSaveOperation:completionHandler:,您的代码运行速度将提高几个数量级。
标签: objective-c ios json sqlite core-data