我的程序从Web服务接收JSON数据。接下来,程序使用Core Data将数据存储在数据库中。如果我在添加每个条目后调用保存数据,一切正常,但速度非常慢。保留200个条目需要一分钟以上。
如果我在结尾只执行一次保存 - 程序抛出异常。
- (void) onLoadMessages:(NSObject*)object {
NSArray *messages = (NSArray*)object;
if (messages==nil) {
[self onError:@"Message array is null"];
return;
}
NSDate *date = [NSDate date];
long now = [date timeIntervalSince1970];
Boolean update = false;
for(int i=0; i<messages.count; i++) {
NSDictionary *m = messages[i];
Message *msg = [[Message alloc]initWithDictionary:m];
if ([self UpdateMessage:msg UpdateTime:now])
update = true;
}
if (update) {
NSError *error = nil;
// Error throw here
if (![self.managedObjectContext save:&error])
[self onError2:error];
}
}
- (Boolean) UpdateMessage:(Message*) msg UpdateTime:(long)now {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Messages" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSString *s = [NSString stringWithFormat:@"%ld", msg.id];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(id=%@)", s];
[fetchRequest setPredicate:pred];
NSError *error;
NSArray *object = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
Boolean result = false;
if (object==nil)
[self onError2:error];
else {
NSManagedObject *m;
if ([object count]==0) {
// Insert new message
m = [NSEntityDescription insertNewObjectForEntityForName:@"Messages"
inManagedObjectContext:self.managedObjectContext];
[m setValue:[NSNumber numberWithLong:msg.id] forKey:@"id"];
[m setValue:[NSNumber numberWithLong:msg.agancy.id] forKey:@"agancy"];
[m setValue:msg.header forKey:@"header"];
[m setValue:msg.keywords forKey:@"keywords"];
[m setValue:[NSNumber numberWithLong:msg.indate] forKey:@"indate"];
[m setValue:[NSNumber numberWithLong:now] forKey:@"updated"];
result = true;
} else {
// Update message
m = [object objectAtIndex:0];
[m setValue:[NSNumber numberWithLong:now] forKey:@"updated"];
}
// Save the context.
// Too long execution
/*NSError *error = nil;
if (![self.managedObjectContext save:&error])
[self onError2:error];*/
}
return result;
}
帮助纠正程序的行为。
尊重, 亚历山大。
P.S。 执行发生在主线程中。
Field&#34; Id&#34;对于表&#34;消息&#34;索引。
答案 0 :(得分:0)
我通过添加privateObjectContext来解决问题!
_privateObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
在更新/插入data /
时替换privateObjectContext上的managedObjectContext