2012-01-04 73 views
0

我想實現搜索UITableView。首先,我在 - (void)viewDidLoad方法中填入數據庫歷史時期的數組。使用numberOfRowsInSection方法的NSPredicate問題

self.periodsArr=[dbAccsess getPeriods:subCountryID]; 
self.searchBar = [[[UISearchBar alloc]initWithFrame: 
        CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)] autorelease]; 
searchBar.delegate=self; 
self.tableView.tableHeaderView = self.searchBar; 
searchBar.keyboardType=UIKeyboardTypeNumberPad; 
self.searchController = [[[UISearchDisplayController alloc] 
          initWithSearchBar:self.searchBar contentsController:self] autorelease]; 
self.searchController.searchResultsDataSource = self; 
self.searchController.searchResultsDelegate = self; 

然後我嘗試實施方法

- (NSInteger)tableView:(UITableView *)utableView numberOfRowsInSection:(NSInteger)section 
{ 
if(utableView==self.tableView) 
{ 
    return [self.periodsArr count]; 
} 
NSPredicate *predicate = [NSPredicate predicateWithFormat: 
          @"period beginswith[c] %@", self.searchBar.text]; 
filteredItems=[[NSMutableArray alloc]init]; 
self.filteredItems=[self.periodsArr filteredArrayUsingPredicate:predicate]; 
return filteredItems.count; 

} 

並在視圖控制器UISearchBarDelegate,UITableViewDataSource,的UITableViewDelegate

在tableCells中的字符串與像1789年至1798年開始的日期。當我嘗試搜索信息時,搜索方法僅適用於第一個數字....例如,我有一個信息以5開頭的單元格。當我輸入UISearchBar數字5時,該方法返回以1.當我鍵入兩個數字時,方法返回「無結果」。問題在哪裏,我哪裏出錯了?

+0

你的「時期」是NSString的一個實例嗎? – LordTwaroog 2012-01-04 19:57:28

+0

@LordTwaroog是的。 – NCFUSN 2012-01-04 20:03:27

+1

嘗試調試,如果self.filteredItems包含您希望的元素。此外,我會將此代碼從NumberOfRowsInSection:方法移出到更相關的位置。注意'filteredItems = [[NSMutableArray alloc] init]中可能存在的內存泄漏;'' - 您不會在此處釋放任何可能的先前值。 – LordTwaroog 2012-01-04 20:30:30

回答

0

嗯,我自己解決了這個問題。我搞砸了cellForRowAtIndexPath方法。