gpt4 book ai didi

cocoa - 是否有一种更节省内存的方法来搜索核心数据数据库?

转载 作者:行者123 更新时间:2023-12-03 17:36:30 24 4
gpt4 key购买 nike

我需要查看我的核心数据数据库中是否存在从 CSV 文件获取的具有唯一标识符的对象,这是我认为适合此任务的代码:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity;
entity =
[NSEntityDescription entityForName:@"ICD9"
inManagedObjectContext:passedContext];
[fetchRequest setEntity:entity];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"uniqueID like %@", uniqueIdentifier];
[fetchRequest setPredicate:pred];
NSError *err;
NSArray* icd9s = [passedContext executeFetchRequest:fetchRequest error:&err];
[fetchRequest release];
if ([icd9s count] > 0) {
for (int i = 0; i < [icd9s count]; i++) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
NSString *name = [[icd9s objectAtIndex:i] valueForKey:@"uniqueID"];
if ([name caseInsensitiveCompare:uniqueIdentifier] == NSOrderedSame && name != nil)
{
[pool release];
return [icd9s objectAtIndex:i];
}
[pool release];
}
}
return nil;

经过更彻底的测试,看来这段代码导致了我正在编写的应用程序中的大量泄漏(它在 3GS 上崩溃,然后才在 1459 个项目中达到 20%)。我觉得这不是最有效的方法,有什么建议可以提高内存效率吗?提前致谢!

最佳答案

  • 请勿在请求谓词中使用 like 运算符。使用=。那应该快得多。
  • 您可以使用 [c] 修饰符通过谓词指定搜索不区分大小写。
  • 没有必要在循环的每次迭代中创建和销毁 NSAutoreleasePool。事实上,可能根本不需要。
  • 您不需要在 for() 循环内进行任何检查。您正在重复谓词的工作。

所以我会将您的代码更改为:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:...];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"uniqueID =[c] %@", uniqueIdentifier]];
NSError *err = nil;
NSArray *icd9s = [passedContext executeFetchRequest:fetchRequest error:&err];
[fetchRequest release];
if (error == nil && [icd9s count] > 0) {
return [icd9s objectAtIndex:0]; //we know the uniqueID matches, because of the predicate
}
return nil;

关于cocoa - 是否有一种更节省内存的方法来搜索核心数据数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4703931/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com