2013-04-30 155 views
0

我的應用程序有大約200個UITableView行,當我在xcode上使用模擬器通過UISearchBar過濾數據時,它立即過濾並顯示結果,但是,當我在我的iphone中運行我的應用程序(iphone4 ,iOS 5.1.1),它會在顯示任何搜索結果之前掛起幾秒鐘。我使用這個代碼過濾數據...SearchBar掛在iphone上,但在模擬器上工作正常

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{ 
[self.filteredData removeAllObjects]; 

if ([searchText length] > 0) { 
    self.isSearching = YES; 
    for (AClass *filteredData in self.allData) { 
     NSRange titleResultRange = [filteredData.name rangeOfString:self.searchBar.text options:NSCaseInsensitiveSearch]; 
     if (titleResultRange.location != NSNotFound) { 
      [self.filteredData addObject:filteredData]; 
     } 
    } 
} 
else self.isSearching = NO; 
[self.tableView reloadData];} 

我相信我的代碼是好的,因爲它的工作完全正常的模擬器,有什麼我需要做,使之更快地適用於iPhone? 順便說一句,我的iPhone工作正常,我使用其他應用程序,他們工作正常..

回答

1

您的設備花費的時間比模擬器更長的原因是由於可用的內存量。作爲一般規則,不要在模擬器中使用應用程序的性能來判斷應用程序的性能。

如果您按照您描述的方式過濾了一個非常大的數據集,我會建議使用分派隊列執行搜索,而不是在主隊列中完成所有操作。你可以在這裏閱讀關於它們的信息:http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html

如果你不想閱讀整個文檔,下面是你的代碼的樣子。

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{ 
    [self.filteredData removeAllObjects]; 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     if ([searchText length] > 0) { 
      self.isSearching = YES; 
      for (AClass *filteredData in self.allData) { 
       NSRange titleResultRange = [filteredData.name rangeOfString:self.searchBar.text options:NSCaseInsensitiveSearch]; 
       if (titleResultRange.location != NSNotFound) { 
        [self.filteredData addObject:filteredData]; 
       } 
      } 
     } 
     else self.isSearching = NO; 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      [self.tableView reloadData]; 
     }); 
    }); 
} 

請注意,我給你的是不是線程安全的例子......你需要確保只有一個搜索在任何給定時間正在執行或該代碼會崩潰,因爲在同一陣列將在多個隊列中被引用。如果您需要更多幫助,請發表評論,我會盡力去解決。

+0

謝謝darkfoxmrd! – DevCali 2013-05-01 01:33:50

相關問題