對於我的iPhone應用程序,我爲Core Data設置了一個數據模型。它包含一個實體Words
,其屬性爲language : String
,length : Integer16
和word : String
。核心數據:獲取項目的速度很慢
我預填充我的模型的SQLite數據庫使用相同的數據模型和應對填充數據庫應用程序的主寫一個單獨的iPhone應用程序單詞列表(200K項目)。
現在使用NSFetchedRequest,我可以按照我喜歡的方式查詢託管對象,但結果很慢。我用下面的方法:
- (NSString *)getRandomWordLengthMin:(int)minLength max:(int)maxLength
{
NSString *word = @"";
MyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Words"
inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSString *predicateString = @"length >= %d AND length <= %d";
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString,
minLength, maxLength];
[fetchRequest setPredicate:predicate];
NSError *error = nil;
int entityCount = [context countForFetchRequest:fetchRequest error:&error];
[fetchRequest setFetchLimit:1];
if(entityCount != 0)
{
[fetchRequest setFetchOffset:arc4random()%entityCount];
}
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
if([fetchedObjects count] != 0)
{
Words * test = [fetchedObjects objectAtIndex:0];
word = [NSString stringWithFormat:@"%@", [test word]];
}
return word;
}
使用我已經在列zLength手動設置相關的指數的SQLite的編輯,但這並沒有帶來任何的加速。瓶頸在哪裏?
編輯:
我想通了,讓int entityCount = ...
是緩慢的。但是,即使讓所有的對象,然後選擇一個隨機字很慢:
Words * test = [fetchedObjects objectAtIndex:arc4random()%[fetchedObjects count]];
謝謝,現在我只提取一個具有固定長度的屬性(最小/最大值顯着減慢)。 – Norbert