从核心数据数据库检索数据的替代方法-iOS [英] Alternate way to retrieve data from core data database - ios
本文介绍了从核心数据数据库检索数据的替代方法-iOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从数据库检索数据时遇到性能问题.
I am having performance issues while retrieving data from the database.
现在,这就是我的方法.
Right now, this is how I do it.
+(NSMutableArray *) searchObjectsInContext: (NSString*) entityName : (NSPredicate *) predicate : (NSString*) sortKey : (BOOL) sortAscending
{
i3EAppDelegate *appDelegate = (i3EAppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
[request setEntity:entity];
[request setFetchBatchSize:5];
//[request setFetchLimit:10];
[request setReturnsObjectsAsFaults:NO];
// If a predicate was passed, pass it to the query
if(predicate != nil)
{
[request setPredicate:predicate];
}
// If a sort key was passed, use it for sorting.
if(sortKey != nil)
{
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:sortAscending];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
}
NSError *error;
NSMutableArray *mutableFetchResults = [[context executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
// Handle the error.
// NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
exit(-1); // Fail
}
[request release];
//[context release];
appDelegate = nil;
return [mutableFetchResults autorelease];
}
是否还有其他方法可以执行相同的操作,但是速度更快?
Is there any other way to perform the same operation but in a faster way?
如果是这样,那么如果有人可以帮助我,那就太好了.
If so, it would be great if someone could help me out in this.
推荐答案
有几个问题:
- 您没有谓词.因此,您正在检索整个表.这可能是您最大的问题.
- 您将在检索时加载所有完整对象.这将大大减慢速度.如果您不需要实现所有对象,则建议重新打开
-setReturnsObjectsAsFaults:
. -
-setFetchBatchSize:
的设置可能没有达到您期望的效果.如果要限制返回的结果数,请使用-setFetchLimit:
- 对
NSArray
结果进行-mutableCopy
没有价值.我怀疑您是从书中得到的,建议您停止这样做.
- You do not have a predicate. Therefore you are retrieving the entire table. That is probably your single biggest issue.
- You are loading all of the full objects on retrieval. This is going to slow things down considerably. If you do not need the entire objects realized then I would suggest turning
-setReturnsObjectsAsFaults:
back on. - The setting of
-setFetchBatchSize:
is probably not having the effect you are expecting. If you want to limit the number of results returned use-setFetchLimit:
- Making a
-mutableCopy
of theNSArray
results has no value. I suspect you got that from a book and recommend you stop doing it.
这篇关于从核心数据数据库检索数据的替代方法-iOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文