2009-07-22 5 views
9

나는 현재 코드조건이 충족되지 않을 경우에 true를 반환하는 자 NSPredicate를 작성

NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF contains '-'"]; 
[resultsArray filterUsingPredicate:pred]; 

이 포함 된 요소 배열을 반환의 다음 조각이 '-'. 나는 이것을 역으로하고 싶기 때문에 '-'를 포함하지 않는 모든 원소가 반환된다.

이것이 가능합니까?

여러 위치에서 NOT 키워드를 사용해 보았지만 아무 소용이 없었습니다. (필자는 어쨌든 Apple 문서를 기반으로 작동하지 않을 것이라고 생각했습니다.)

더 나아가 배열의 요소에 포함되지 않기를 바라는 문자 배열을 사용하여 술어를 제공 할 수 있습니까? 배열은 문자열로드입니다.

+0

변경된 제목이이 질문에 무엇을 묻는 지 잘 반영합니다. –

답변

27

저는 Objective-C 전문가가 아니지만 documentation seems to suggest this is possible입니다. 당신은 시도 :

predicateWithFormat:"not SELF contains '-'" 
+0

감사합니다. 전적으로 문서를 읽지 않아도됩니다. 내가 시험하지 않은 유일한 곳은 자기 앞에 있었어! – JonB

+0

기꺼이 도와 드리겠습니다. :) –

+0

+1, Sweeeeeeet! – EmptyStack

8

당신은 당신이 이미 가지고있는 술어를 부정하는 사용자 정의 술어를 구축 할 수 있습니다. 당신이 통과하고 구축 할 수 있도록,

NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF contains '-'"]; 
NSPredicate *notPred = [NSCompoundPredicate notPredicateWithSubpredicate:pred]; 
[resultsArray filterUsingPredicate:pred];

NSCompoundPredicate 수준의 지원 AND, OR 및 NOT 조건 유형 : 실제로, 기존 술어를 취하고 및 NOT 연산자처럼 작동 다른 조건에서 포장 배열에서 원하지 않는 모든 문자를 가진 큰 복합 술어를 필터링 한 다음 필터링하십시오. 같은 시도 : 그래도, 효율성에 대해 어떠한 보증도하지 않습니다, 그것은 아마도 먼저 최종 배열에서 가장 문자열을 제거 할 가능성이 문자를 넣어하는 것이 좋습니다

// Set up the arrays of bad characters and strings to be filtered 
NSArray *badChars = [NSArray arrayWithObjects:@"-", @"*", @"&", nil]; 
NSMutableArray *strings = [[[NSArray arrayWithObjects:@"test-string", @"teststring", 
        @"test*string", nil] mutableCopy] autorelease]; 

// Build an array of predicates to filter with, then combine into one AND predicate 
NSMutableArray *predArray = [[[NSMutableArray alloc] 
            initWithCapacity:[badChars count]] autorelease]; 
for(NSString *badCharString in badChars) { 
    NSPredicate *charPred = [NSPredicate 
         predicateWithFormat:@"SELF contains '%@'", badCharString]; 
    NSPredicate *notPred = [NSCompoundPredicate notPredicateWithSubpredicate:pred]; 
    [predArray addObject:notPred]; 
} 
NSPredicate *pred = [NSCompoundPredicate andPredicateWithSubpredicates:predArray]; 

// Do the filter 
[strings filterUsingPredicate:pred];

을 필터 할 수 있도록 가능한 한 많은 회로를 단락시킨다.

관련 문제