2011-12-11 48 views
1

當我嘗試過濾字符串數組我沒有得到匹配的值有一個?在使用filteredArrayUsingPredicate時:你可以用URL替換一個句子,你仍然會得到同樣的結果。過濾NSArray無法正常工作時?是在NSString

這裏的簡化代碼:

-(void)test { 

    NSArray *theURLs = [NSArray arrayWithObjects:@"http://www.google.com", @"http://www.google.com?test=1", nil]; 

    NSString *currentURL = @"http://www.google.com?test=1"; 
    NSLog(@"currentURL %@", currentURL); 
    NSPredicate *matchURLPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES[cd] %@", [currentURL lowercaseString]]; 
    NSLog(@"match predicate %@", matchURLPredicate); 
    NSArray *filteredArray = [theURLs filteredArrayUsingPredicate:matchURLPredicate]; 
    NSLog(@"filtered array %@", filteredArray); 
    if ([filteredArray count]== 0) { 

     NSLog(@"http://www.google.com?test=1 should have been found, but was not"); 

    } else { 

     NSLog(@"http://www.google.com?test=1 was found"); 

    } 

} 

如果我看的只是@「http://www.google.com」它過濾就好了。

下面是更正後的代碼:

-(void)test { 

    NSArray *theURLs = [NSArray arrayWithObjects:@"http://www.google.com", @"http://www.google.com?test=1", nil]; 

    NSString *currentURL = @"http://www.google.com\\?test=1"; 
    NSLog(@"currentURL %@", currentURL); 
    NSPredicate *matchURLPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES[cd] %@", [currentURL lowercaseString]]; 
    NSLog(@"match predicate %@", matchURLPredicate); 
    NSArray *filteredArray = [theURLs filteredArrayUsingPredicate:matchURLPredicate]; 
    NSLog(@"filtered array %@", filteredArray); 
    if ([filteredArray count]== 0) { 

     NSLog(@"http://www.google.com?test=1 should have been found, but was not"); 

    } else { 

     NSLog(@"http://www.google.com?test=1 was found"); 

    } 

} 

回答

1

?可能是一個特殊字符。只是逃避它:

@"http://www.google.com\\?test=1" 
+0

謝謝,我曾試過一次逃生,但沒有意識到兩個將需要。 – Chad

+0

@Chad:需要兩個,因爲一個被字符串文字吃掉。 – Dani

相關問題