2012-04-02 50 views
0

我想過濾包含「some」字符串的NSMutableArray元素。 ListArchives中填充了字符串元素,listFiles必須是過濾後的字符串元素。 XCode在最後發佈的行中生成警報。什麼做錯了?任何其他方法來過濾NSMutableArray的元素?xcode過濾NSMutableArray元素的字符串內容

NSString *match = @"*some*"; 
listFiles = [[NSMutableArray alloc] init]; 

NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF like[cd] %@", match]; 

listFiles = [listArchives filteredArrayUsingPredicate:sPredicate]; 

回答

4

嘗試使用的contains代替like,舉例如下:

NSString *match = @"some"; 
listFiles = [[NSMutableArray alloc] init]; 

NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", match]; 

listFiles = [[listArchives filteredArrayUsingPredicate:sPredicate] mutableCopy]; 
+0

好吧,似乎更好的選擇。但仍然顯示警告,「不可分割的指針類型分配給來自NSArray的NSMutableArray _strong」。所以如果我聲明listFiles爲NSArray解決它,但沒有其他方式讓listFiles也可變? – Jaume 2012-04-02 17:14:34

+0

@Jaume這是因爲編譯器不知道已過濾的數組是否爲'NSMutableArray'。試試這個,而不是最後一行:'[listFiles setArray:[listArchives filteredArrayUsingPredicate:sPredicate]];' – dasblinkenlight 2012-04-02 17:19:12

+0

哦,當然可以!懶惰的評論從我自己:)我真的讚賞你的幫助! – Jaume 2012-04-02 17:23:23

2

如果你要搜索爲 '喜歡' 操作。 比方說你有一個NSArray中有如下內容:

static int count = 0; 
NSArray *results = [NSArray arrayWithObjects:@"What was", @"What is", @"What will", nil]; 

NSString *targetString = @"What" 
for (NSString *strObj in results) 
{ 
    if ([strObj rangeOfString:targetString].location != NSNotFound){ 
     NSLog (@"Found: %@", strObj); 
     count = count + 1;    
    } 
} 
NSLog(@"There were %d occurence of %@ string",count,targetString); 
0
NSString *match = @"some"; 
listFiles = [[NSMutableArray alloc] init]; 
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@", match]; 
listFiles = [listArchives filteredArrayUsingPredicate:sPredicate]; 

對於強大的搜索這可以成爲你一些什麼樣的「Like」服務於SQL