2012-05-20 2 views
3

내 질문 : NSFetchRequest을 코어 데이터가있는 여러 페치에 재사용해도 좋지 않니?코어 데이터와 함께 여러 페치에 대해 NSFetchRequest를 재사용하는 데 나쁜 점이 있습니까?

예제 코드 :

NSFetchRequest *request = [[NSFetchRequest alloc] init]; 

NSEntityDescription *logEntity = [NSEntityDescription entityForName:@"LogEntry" inManagedObjectContext:context]; 
[request setEntity:logEntity]; 

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"dateTimeAction" ascending:NO]; // ascending NO = start with latest date 
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]]; 

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"status == %@",@"op tijd"]; 
[request setPredicate:predicate]; 
[request setFetchLimit:50]; 

NSError *error = nil; 
NSInteger onTimeCount = [context countForFetchRequest:request error:&error]; 

NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"status == %@",@"uitgesteld"]; 
[request setPredicate:predicate1]; 
[request setFetchLimit:50]; 

NSInteger postponedCount = [context countForFetchRequest:request error:&error]; 

NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"status == %@",@"gemist"]; 
[request setPredicate:predicate2]; 
[request setFetchLimit:50]; 

NSInteger missedCount = [context countForFetchRequest:request error:&error]; 

답변

5

문제는 아니지만 주어진 예제에서는 많은 코드가 필요하지 않습니다. 가져 오기 요청을 생성하는 데 가장 비용이 많이 드는 부분은 조건 자 형식 문자열을 구문 분석하는 것입니다.

자주라고 준, 당신이 그것을 속도를 찾고있는 코드가, 여기에 몇 가지 아이디어가 있다면 시도 :

  • 모든 술어를 작성하고 한 번만 요청을 가져 오기 : 어쩌면에 dispatch_once() 블록을 만들고 정적으로 저장합니다. 또는 생성자에 저장되고 객체 필드에 저장됩니다.
  • 카운트에만 관심이있는 경우 순서는 중요하지 않으므로 정렬 설명자를 지정하지 마십시오.
  • 실제 조건이 표시된 것보다 더 복잡하거나 유연한 경우 대체 변수가있는 일] 템플리트 술어와 predicateWithSubstitutionVariables:을 사용하여 지정된 사본을 생성하십시오.
  • 코드 간결성을 더 높이려면 모델 편집기를 사용하여 개체 모델에서 해당 템플릿을 정의하고 fetchRequestFromTemplateWithName:substitutionVariables:을 사용하여 패치 요청을 만듭니다.

원하는 경우 일부 샘플 코드를 작성할 수 있습니다.

+0

[request setFetchLimit : 50];과 결합하여 최신 50 개의 요소를 가져 오려면 정렬 설명자가 필요합니다. 나는 모든 요청에 ​​대해 fetchLimit을 한 번 설정할 수 있다고 생각한다. – Pieter

+0

아. 그런 다음 FR을 재사용하여 나중에 실제 로그 항목을 가져오고 표시된대로 계산하면 개체 가져 오기 중에 정렬 설명자를 설정하고 카운트를 가져 오는 동안 nil로 다시 설정하는 것이 좋습니다. 50 개가 넘는 경우 카운트 가져 오기는 "어떤 것"이든 관계없이 50을 반환합니다. – rgeorge

1

NSFetchedRequest 그냥 검색 기준 기술자이기 때문에 나는 또한이 같은 귀하의 인출 요청에 여러 조건을 가질 수 있습니다, 그것은 문제가 있다고 생각하지 않는다 :

NSPredicate *predicates = [NSCompoundPredicate andPredicateWithSubpredicates:NSArray_of_predicates];