核心数据更新(如果存在)或创建新的托管对象。我可以加快速度吗?

时间:2011-01-22 04:50:17

标签: iphone core-data nspredicate

我有以下代码,我想知道是否有任何方法可以加快速度。基本上我的应用程序从网上下载一些JSON(大约4000条记录),并根据数据更新或创建我的托管对象。目前它很慢,我可以看到原因,但我是核心数据的新手,所以我想知道我能做些什么才能让它更快?

 NSFetchRequest *request = [[NSFetchRequest alloc] init];
 NSEntityDescription *entity = [NSEntityDescription entityForName:@"Company" inManagedObjectContext:managedObjectContext];
 [request setEntity:entity];
 NSMutableArray *coreDataArray = [[managedObjectContext executeFetchRequest:request error:nil] mutableCopy];
 [request release];

 for (NSDictionary *dict in arr) {
  NSArray *filtered = [coreDataArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(code == %@)", [dict objectForKey:@"Code"]]];
  //NSLog(@"COREDATA ARRAY: %d FILTERED ARRAY: %d CODE: %@ COREDATA FIRST CODE: %@", [coreDataArray count], [filtered count], [dict objectForKey:@"Code"], [[coreDataArray objectAtIndex:0] code]);
  if ([filtered count] > 0) {
   Company *c = [filtered objectAtIndex:0];
   if ([dict objectForKey:@"Defunct"]) {
    NSLog(@"DELETED DEFUNCT COMPANY");
    [managedObjectContext deleteObject:c];
   } else {
    [c populateWithJSONDictionary:dict];
   }
  } else {
   Company *c = (Company *)[NSEntityDescription insertNewObjectForEntityForName:@"Company" inManagedObjectContext:managedObjectContext];
   [c populateWithJSONDictionary:dict];
  }

  float percent = (float)[arr indexOfObject:dict]/[arr count];
  [self performSelectorInBackground:@selector(updateProgressView:) withObject:[NSString stringWithFormat:@"%f",percent]];
 }

 [coreDataArray release];

非常感谢您提供任何帮助。

1 个答案:

答案 0 :(得分:2)

您应该查看Core Data Programming Guide: Performance部分

它对数据导入性能有一些具体的建议。

如果Apple再次移动文档,这是Google site:developer.apple.com core data import performance

上的一个很好的搜索查询