2012-04-10 7 views
7

NSPredicateを使用して、大文字と小文字を区別せず、区別しない2つの文字列を一致させる必要があります。と空白を区別しない空白を無視するNSPredicate

述語は次のようになります:

[NSPredicate predicateWithFormat:@"Key ==[cdw] %@", userInputKey]; 

「W」修飾子は、私が使用したいものを表現するために考案一つです。

データソースの「Key」値にも空白が含まれている可能性があります(これらの空白が必要です。あらかじめトリミングすることはできません)。userInputKeyをトリミングできません。

たとえば、userInputKey「abc」と指定すると、述語はすべて

{"abc", "a b c", " a B C "}
のように一致する必要があります。 userInputKey "a B C"とすると、述部は上記の集合のすべての値と一致する必要があります。

これはそれほど難しいことではありませんか?

答えて

11

このようなものの定義についてどのように:

+ (NSPredicate *)myPredicateWithKey:(NSString *)userInputKey { 
    return [NSPredicate predicateWithBlock:^BOOL(NSString *evaluatedString, NSDictionary *bindings) { 
     // remove all whitespace from both strings 
     NSString *strippedString=[[evaluatedString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:@""]; 
     NSString *strippedKey=[[userInputKey componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:@""]; 
     return [strippedString caseInsensitiveCompare:strippedKey]==NSOrderedSame; 
    }]; 
} 

を次に、このようにそれを使用します。

NSArray *testArray=[NSArray arrayWithObjects:@"abc", @"a bc", @"A B C", @"AB", @"a B d", @"A  bC", nil]; 
NSArray *filteredArray=[testArray filteredArrayUsingPredicate:[MyClass myPredicateWithKey:@"a B C"]];    
NSLog(@"filteredArray: %@", filteredArray); 

結果は次のとおりです。

2012-04-10 13:32:11.978 Untitled 2[49613:707] filteredArray: (
    abc, 
    "a bc", 
    "A B C", 
    "A  bC" 
) 
+0

私は、HTTPをルックアップする必要がありました:// stackoverflowの.com/questions/3543208/nsfetchrequest-and-predicatewithblock私はNSFetchRequestで述語を使用したかったので、しかし、それ以外のあなたのsolutio nは美しく働いた。ありがとう! – JiaYow