关于上下文保存的CoreData性能

时间:2010-01-16 10:38:52

标签: iphone core-data

我完成了将我的应用转换为将CoreData层用于我想要使用的小型数据仓库。我对性能以及如何最好地使用它有一些担忧。特别是: 我有很多运行,我从文件中的磁盘属性读取:每个属性应该生成一个新对象,除非该类型的对象和该值已经存在。因此,对于我读取的每个文件,我:执行一次提取以检查该托管对象是否已经存在;如果是,则完成,否则我创建对象,赋值并保存上下文。

目前,我每次创建一个新对象时都会保存一次上下文,因此每次读取文件(可能是数百个)会发生或多或少十次(对于十个属性)。最好是减少上下文保存点,可能一次用于文件而不是属性一次?我不知道这个操作的开销,所以我不知道是否可以经常这样做,或者如何找出花在这上面的时间(也许用仪器?不知道怎么做)。

2 个答案:

答案 0 :(得分:11)

设置每个属性后无需保存。

通常,只有在代码完成后才能保存托管对象,因为保存会重置撤消。在您描述的设置中,您可以安全地生成数百个托管对象,然后将其保存到永久存储中。您可以在内存中拥有大量(数千个)轻量级(文本属性)对象,而不会给iPhone带来任何压力。

iPhone上唯一的问题是你永远不知道应用程序何时被暂停或关闭。这使得保存比在其他平台上更常见。但是,不是你现在使用的程度。

指南的

Core Data Performance section可能会帮助您进行规划。 Instruments允许您查看Core Data性能的详细信息。

但是,在你用大量数据测试应用程序并发现它很慢之前,我不会做任何事情。过早优化是万恶之源。不要浪费时间试图防止你可能没有的问题。

答案 1 :(得分:3)

为防止“突然停止应用程序”问题,您可以实现类似该方法的内容:

- (void)saveContext {

NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;


if (managedObjectContext != nil) {
    if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
         */
        LogError(@"Unresolved error %@, %@", error, [error userInfo]);
            // abort();
    } 
}

}

并在app委托的两个方法中使用它:

- (void)applicationWillTerminate:(UIApplication *)application;

- (void)applicationDidEnterBackground:(UIApplication *)application;

认为它可能不是100%的解决方案,但在大多数情况下它会完成工作......