0

我正在优化我的第一个 iOS 应用程序,然后才进入商店,并注意那些看似花费大量时间的方法。我有一个相当简单的主从应用程序,其中来自 Core Data SQLite 的实体显示在 a 中UITableView,然后点击一个会显示一个详细视图,用户可以在其中将其标记为收藏(BOOL在该对象中设置一个标志为YES。他们点击了他们最喜欢的按钮,我打电话[NSManagedObjectContext save]以确保他们的更改立即得到反映,并且在计划外终止的情况下,等等。

在我的 iPhone 4S 上进行测试时,此save操作目前大约需要 205 毫秒。数据库中有大约 4,500 个条目,每个条目都有一些字符串和一些布尔值(包装在NSNumbers 中)。

第一个问题:进行此更改是否需要 200 毫秒?我只设置一个布尔值,然后保存上下文,但我以前从未使用过 Core Data,所以我不知道这是否正常。

第二个问题:我正在使用的代码如下 - 我在代码中做错了什么以使方法需要这么长时间才能执行吗?

- (IBAction) makeFavorite: (id) sender
{
    [self.delegate detailViewControllerDidMakeFavorite];
    [_selectedLine setIsLiked: [NSNumber numberWithBool: YES]];
    [_selectedLine setIsDisliked: [NSNumber numberWithBool: NO]];
    NSError *error;
    if (![[[CDManager sharedManager] managedObjectContext] save:&error]) NSLog(@"Saving changes failed: %@, %@", error, [error userInfo]);
}

也许我什么都不担心(我仍然是一个相对较新的程序员),但更广泛地说,200 毫秒足以让我至少尝试解决这个问题,对吧?:)

4

2 回答 2

1

Consider UIManagedDocument. It automatically handles saving in a background context. I especially recommend it if you are on iOS 6. If you are not passing object IDs around, or merging with other contexts, then you should be able to use it fairly easily and reliably.

Your simple use case seems tailor made for it.

于 2013-04-15T19:04:58.040 回答
0

1) 是否应该保存一次布尔值更改需要 200 毫秒?

是的,可能需要这么长时间。您正在执行 IO 操作并根据文档

When Core Data saves a SQLite store, SQLite updates just part of the store file. Loss of that partial update would be catastrophic, so you may want to ensure that the file is written correctly before your application continues. Unfortunately, doing so means that in some situations saving even a small set of changes to an SQLite store can take considerably longer than saving to, say, an XML store.

-

2) am I doing something wrong in the code to make the method take this long to execute?

No. you are making the save to the store (under the assumption you have no parent context).

-

3) Are 200ms enough for me to at least try to address this issue?

Yes. 200ms are a noticeable time for a human, and will be felt. you could try and perform the save in the background, but this is unsafe according to the documentation. or, move it to the end of the entire object editing.

My advise would be to read and see if you could make some compromises in your context architecture (your CoreData stack structure).
From my experience, saving in the background is not that bad.

于 2013-04-15T16:43:50.660 回答