2011-04-25 20 views
1

我正試圖優化針對核心數據的提取請求。針對最近修改的對象優化的核心數據提取

我有一個名爲lastModifiedDate屬性的實體,它是一個NSDate對象。我需要查詢我的數據庫中最新的lastModifiedDate屬性。我有下面的代碼,它可以在小數據集中正常工作,但是有一個擁有40k記錄的數據庫,這個查詢就像廢話一樣運行。

NSDate *mostRecentLastModifiedDate = nil; 
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:entityName inManagedObjectContext:self.managedObjectContext]; 

NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
[request setEntity:entityDescription]; 
[request setFetchLimit:1]; 
[request setPropertiesToFetch:[NSArray arrayWithObject:@"lastModifiedDate"]]; 

NSSortDescriptor *dateSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastModifiedDate" ascending:NO]; 

[request setSortDescriptors:[NSArray arrayWithObject:dateSortDescriptor]]; 
[dateSortDescriptor release]; 

NSError *error = nil; 
NSArray *result = [self.managedObjectContext executeFetchRequest:request error:&error]; 
if (error) { 
    NSLog(@"Error fetching most recent lastModifiedDate property for %@ entity, error details: %@", entityName, error); 
} else if ([result count] > 0) { 
    mostRecentLastModifiedDate = [[[[result objectAtIndex:0] valueForKey:@"lastModifiedDate"] copy] autorelease]; 
} else { 
    mostRecentLastModifiedDate = [NSDate distantPast]; 
} 

[request release]; 

return mostRecentLastModifiedDate; 

回答

1

閱卷lastModifiedDate屬性作爲數據模型索引使這個查詢非常快,仍然是有興趣,如果有更好的方法來做到這一點,雖然。