我正在使用核心数据库来保存我从Web服务返回到我的应用程序的数据。但这非常缓慢。知道这是怎么来的吗?我所做的是以下内容。我有一个从Web服务获取数据的类。就像你可以在这看到的一样。
GenkData.h
+ (NSArray *)getNews;
GenkData.m
+ (NSDictionary *)executeGenkFetch:(NSString *)query
{
query = [NSString stringWithFormat:@"%@", query];
query = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// NSLog(@"[%@ %@] sent %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), query);
NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error] : nil;
if (error) NSLog(@"[%@ %@] JSON error: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription);
// NSLog(@"[%@ %@] received %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), results);
return results;
}
+ (NSArray *)getNews
{
NSString *request = [NSString stringWithFormat:@"http://www.krcgenk.be/mobile/json/request/news/type/ipad"];
return [[self executeGenkFetch:request] valueForKey:@"news"];
}
然后在我显示的第一个视图控制器中,我有一个方法可以在我的核心数据库中获取数据。
- (void)fetchGenkDataIntoDocument:(UIManagedDocument *)document
{
NSLog(@"Fetch data");
dispatch_queue_t fetchQ = dispatch_queue_create("Genk fetcher", NULL);
dispatch_async(fetchQ, ^{
NSArray *news = [GenkData getNews];
[document.managedObjectContext performBlock:^{ // perform in the NSMOC's safe thread (main thread)
int newsId = 0;
//int trainingIndex = -1;
for (NSDictionary *genkInfo in news) {
NSLog(@"Begint met nieuwsitem");
newsId++;
[News newsWithGenkInfo:genkInfo inManagedObjectContext:document.managedObjectContext withNewsId:newsId];
NSLog(@"Einde met nieuwsitem");
}
}];
});
NSLog(@"einde fethdata");
}
接下来,我有一个新闻的NSManagerd对象子类的类别,我将执行以下操作。
+ (News *)newsWithGenkInfo:(NSDictionary *)genkInfo
inManagedObjectContext:(NSManagedObjectContext *)context
withNewsId:(int)newsId
{
News *news = nil;
news = [NSEntityDescription insertNewObjectForEntityForName:@"News"
inManagedObjectContext:context];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT+0:00"]];
NSDate *date = [dateFormatter dateFromString:[genkInfo objectForKey:NEWS_DATE]];
news.title = [genkInfo objectForKey:NEWS_TITLE];
news.date = date;
news.genk_description = [genkInfo objectForKey:NEWS_DESCRIPTION];
news.imgurl = [genkInfo objectForKey:NEWS_IMGURL];
news.shortdescription = [genkInfo objectForKey:NEWS_SHORTDESCRIPTION];
news.url = [genkInfo objectForKey:NEWS_URL];
news.imagecopyright = [genkInfo objectForKey:NEWS_IMAGECOPYRIGHT];
news.news_id = [NSNumber numberWithInt:newsId];
return news;
}
我正在为10个不同的实体做10次以下的过程。所有这些属性主要是字符串。仍然需要花费10分钟来加载所有数据。有人可以帮帮我吗?
亲切的问候。
答案 0 :(得分:0)
Dima回答用分析器检查帮助我解决了这个问题并解决了我的问题