2010-04-15 3 views
6

NSPredicate를 구축하는 가장 좋은 방법은 일부 필터가 선택적인지 여부입니다.필터 용 NSPredicate 구축

이것은 필터 기본적으로, 그래서 몇 가지 옵션이 선택되지 않은 경우 나는 그들

등을 기준으로 필터링 할 수 없습니다. 필터에 대해 option1 및 option2가 설정된 경우.

자 NSPredicate 술어 * = [자 NSPredicate predicateWithFormat @ "= 옵션 1 옵션 2 % @ AND = % @] ....

단지 자 NSPredicate 술어 * = [자 NSPredicate predicateWithFormat 옵션 1을, 그렇지 않은 경우 : @"옵션 1 = % @] ....

키에는 필터링 할 10 가지 옵션이 있으므로 10x10 가능한 조합을 코딩하지 않아도됩니다.

감사

답변

17

John에게 전달하는 것입니다. 다음 템플릿으로 하위 조건 "와 당신은 좋은 조직 술어 템플릿 집합을 유지하기 위해 사전을 사용할 수있는 필터링을

/* Retain these predicate templates as properties or static variables */ 
NSPredicate *optionOneTemplate = [NSPredicate predicateWithFormat:@"option1 = $OPTVALUE"]; 
// .. and so on for other options 

NSMutableArray *subPredicates = [NSMutableArray arrayWithCapacity:10]; 

/* add to subPredicates by substituting the current filter value in for the placeholder */ 
if (!!optionOneValue) { 
    [subPredicates addObject:[optionOneTemplate predicateWithSubstitutionVariables:[NSDictionary dictionaryWithObject:optionOneValue forKey:@"OPTVALUE"]]]; 
} 
// .. and so on for other option values 

/* use the compound predicate to combine them */ 
NSPredicate *filterPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates]; 

// Now use your filterPredicate 

을 수행하는 복합 술어를 구축하기 위해 논리 가지를 사용하지만, 위의 예 기본 단계를 보여줍니다.

Rob. 이 작품 완전히 사실

+0

프리디 케이트 템플릿을 정적 변수로 유지하는 방법에 대한 아이디어를 더 많이 개발할 수 있습니까? –

1

predicateWithFormat:이있는 NSString 걸립니다. 그래서 당신이해야 할 일은 NSMutableString에 추가하기위한 for-loop를 사용하여 선택된 옵션들을 기반으로 문자열을 만들고 그것을 predicateWithFormat:

+1

확실하지 그게 전부 : [fetchRequest setPredicate : [자 NSPredicate predicateWithFormat : @ "startTime을> = % @"에서]]; 이 충돌 : [fetchRequest setPredicate : [NSPredicate predicateWithFormat : [NSString stringWithFormat : @ "startTime> = % @", from]]]; – John

+0

John :'stringWithFormat :'을 추가했기 때문입니다. 그러지 마. Diederik이 대신 제안한 것을 수행하십시오 (또는 루프를 수행하는'componentsJoinedByString :'을 사용하십시오). –