我已经复制了所有本地联系人并将其存储在核心数据中,现在当我使用时间分析器工具时,它显示我花了大量时间从我的应用程序中删除本地联系人。任何人都建议我进行任何优化提高我的代码和应用程序性能的技术。
以下是我从核心数据中删除联系人的代码:
+(void)deleteContacts
{
[[LoadingIndicator currentIndicator]displayActivity:@"Deleting Old contacts"];
//fetch the data from core data and delete them because you are going to sync again
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSManagedObjectContext *managedObjectContext=[appDelegate managedObjectContext];
fetchRequest.entity = [NSEntityDescription entityForName:@"PersonEvent" inManagedObjectContext:managedObjectContext];
NSInteger *contactsIdentifier=1;
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"sourceflag == %d", contactsIdentifier];
NSArray * persons = [managedObjectContext executeFetchRequest:fetchRequest error:nil];
//error handling goes here
if (persons.count>0) {
for (NSManagedObject * person in persons) {
[managedObjectContext deleteObject:person];
}
}
NSError *saveError = nil;
[managedObjectContext save:&saveError];
[[LoadingIndicator currentIndicator]displayCompleted:@"Done"];
[[LoadingIndicator currentIndicator]hide];
NSLog(@"Finished deleting local contacts..");
}
时间分析器显示我花了94.3%的时间 [managedObjectContext save:& saveError];
任何帮助将不胜感激
由于
答案 0 :(得分:0)
首先,我想说“好问题”。并欣赏您关心的事情。
答案: -
在核心数据中,managedObjectContext仍保留同一对象中的所有更改,而不是将其更新为实际数据库。
因此,当[managedObjectContext save:&saveError]
调用它时,它开始将其更新为核心数据库。所以你可以通过以下方式进行优化。检查时间档案表现。
NSError *saveError = nil;
if (persons.count>0) {
for (NSManagedObject * person in persons) {
[managedObjectContext deleteObject:person];
[managedObjectContext save:&saveError];
}
}
[[LoadingIndicator currentIndicator]displayCompleted:@"Done"];
[[LoadingIndicator currentIndicator]hide];
NSLog(@"Finished deleting local contacts..");
希望它可以帮助你......!
答案 1 :(得分:0)
也许PersonEvent
实体具有配置了Cascade
删除规则的关系?也许甚至这些关系另一边的对象都有类似的删除规则?核心数据将单独触发所有这些故障。
在这种情况下,您应该在获取要删除的对象时预取这些关系:
fetchRequest.relationshipKeyPathsForPrefetching
= @[@"relationshipName",
@"anotherRelationship",
@"anotherRelationship.subrelationship"];
如果没有与PersonEvent
一起删除级联中的对象,并且您只删除了大量PersonEvent
,则可以尝试批量保存。这可能不会减少保存所有删除所需的总时间,但它不会锁定上下文,持久性存储协调器和存储文件本身以进行大量保存。
const NSUInteger kBatchSize = 200;
NSUInteger currentCount = 0;
for (NSManagedObject *person in persons) {
currentCount++;
[context deleteObject:person];
if (currentCount == kBatchSize) {
currentCount = 0;
NSError *error;
BOOL saved = [context save:&error];
}
}
if (currentCount != 0) {
NSError *error;
BOOL saved = [context save:&error];
}