2012-04-18 97 views
0

在我的應用程序中,我有一個大約20,000個項目的大表。我在桌面上顯示它。但搜索欄在進行動態搜索時速度太慢。我已經讀過,NSPredicate方法是高性能的,然後是NSRange。 我不知道如何應用這種方法。nspredicate的快速研究

我的代碼是:

- (void)filterContentForSearchText:(NSString*)searchText 
{ 
    [self.filteredListContent removeAllObjects]; 

    for (Book *book in listContent) 
    { 
     NSRange range = [book.name rangeOfString:searchText options:NSCaseInsensitiveSearch]; 
     // is very very slow 
     if (range.location != NSNotFound) 
     { 
      [self.filteredListContent addObject:book]; 
     } 
    } 
} 

如果我必須插入NSPredicate,到我們離開 「爲」?

回答

2
- (void)filterContentForSearchText:(NSString*)searchText 
{ 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains %@", searchText ]; 
    self.filteredListContent = [NSMutableArray arrayWithArray:[listContent filteredArrayUsingPredicate:predicate]]; 
} 
+0

對於aswer,我推這個代碼?進入「換」週期? – 2012-04-18 10:52:35

+0

而不是循環。這取代了循環。 – ssteinberg 2012-04-18 10:53:58

+0

好的,但我管理對象書? @「book.name包含%@」,是嗎? – 2012-04-18 10:56:41

2

如果,例如NSArray的過濾,就可以使用

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"job == 'Programmer'"] 
[listOfItems filterUsingPredicate:predicate]; 

如果你想獲取請求使用

NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title == %@", aTitle]; 
[request setEntity:[NSEntityDescription entityForName:@"DVD" inManagedObjectContext:moc]]; 
[request setPredicate:predicate]; 

NSError *error = nil; 
NSArray *results = [moc executeFetchRequest:request error:&error]; 
// error handling code 
[request release]; 

編輯:

ssteinberg的例子很簡單,好,只有一個音符 - 您可以使用方括號內的關鍵字符c和d來修改操作符o分別指定病例和變音不敏感性。示例[NSPredicate predicateWithFormat:@"name contains[cd] %@", searchString];