批量更新&偶尔插入(coredata) - 太慢了

时间:2009-11-25 09:18:04

标签: iphone objective-c arrays unique

更新:目前正在研究NSSET的minusSet 链接:Comparing Two Arrays

大家好,

可以从你的智慧中受益..

我在我的应用程序中使用Coredata,首次启动时我下载了一个数据文件并插入了500多个对象(每个对象有60个属性) - 快速,没问题。

每次后续启动我都会下载该文件的更新版本,我需要更新所有现有对象的属性(可能除了5个属性),并为已添加到下载文件中的项目创建新文件。

所以,首先发布我得到500个对象..说一周后我的文件现在包含507个项目..

我创建了两个数组,一个用于现有,另一个用于下载。

    NSArray *peopleArrayDownloaded = [CoreDataHelper getObjectsFromContext:@"person" :@"person_id" :YES :managedObjectContextPeopleTemp];
NSArray *peopleArrayExisting = [CoreDataHelper getObjectsFromContext:@"person" :@"person_id" :YES :managedObjectContextPeople];

如果每个数组的计数相等,那么我就这样做:

    NSUInteger index = 0;
if ([peopleArrayExisting count] == [peopleArrayDownloaded count]) {
    NSLog(@"Number of people downloaded is same as the number of people existing");
    for (person *existingPerson in peopleArrayExisting) {
        person *tempPerson = [peopleArrayDownloaded objectAtIndex:index];
        //  NSLog(@"Updating id: %@ with id: %@",existingPerson.person_id,tempPerson.person_id);
        // I have 60 attributes which I to update on each object, is there a quicker way other than overwriting existing?
        index++;
    }
} else {
    NSLog(@"Number of people downloaded is different to number of players existing");

现在是缓慢的部分。

我最终使用它(太慢了):

            NSLog(@"Need people added to the league");
        for (person *tempPerson in peopeArrayDownloaded) {
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"person_id = %@",tempPerson.person_id];
            //  NSLog(@"Searching for existing person, person_id: %@",existingPerson.person_id);
            NSArray *filteredArray = [peopleArrayExisting filteredArrayUsingPredicate:predicate];
            if ([filteredArray count] == 0) { 
                NSLog(@"Couldn't find an existing person in the downloaded file. Adding..");
                person *newPerson = [NSEntityDescription insertNewObjectForEntityForName:@"person" inManagedObjectContext:managedObjectContextPeople];

有没有办法生成一个新的索引项数组,引用我下载的文件中的其他项?

顺便说一句,在我的tableViews上我使用的是NSFetchedResultsController,所以更新属性会调用[cell setNeedsDisplay]; ..每个单元约60次,不是一件好事,它可以使应用程序崩溃。

感谢阅读:)

1 个答案:

答案 0 :(得分:3)

我首先要说的是,我仍然是使用核心数据框架的新手,但我猜你的问题在于你发布的for循环。

如果查看循环,每次执行它时都会创建一个新的NSPredicate对象,然后过滤现有的数组以查找匹配项。在一个小数据集上,这种技术可以解决看似很小的性能损失;但是,使用大型数据集,您最终会花费大量时间创建仅与您提供的名称不同的NSPredicate对象。我建议您查看如何创建单个谓词,然后使用变量替换来执行搜索。有关谓词中变量使用的信息,请查看:http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/CoreData/Articles/cdImporting.html#//apple_ref/doc/uid/TP40003174

作为旁注,您还可以考虑如何对数据进行排序以及如何执行搜索操作。我注意到的另一件事是你没有释放你的NSPredicate对象,所以你也只是扔掉了记忆。

相关问题