2011-05-30 80 views
0

我創建的實現代碼如下一個搜索欄,但我有這個方法的委託問題,因爲我填補另一個數組內部數組表視圖......我告訴我的代碼:IOS:搜索欄在tableview中

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText 
{ 
ProgramAppDelegate *appDelegate = (ProgramAppDelegate *)[[UIApplication sharedApplication] delegate]; 
[tableData removeAllObjects];// remove all data that belongs to previous search 
if([searchText isEqualToString:@""] || searchText==nil){ 
    [myTableView reloadData]; 
    return; 
} 
NSInteger counter = 0; 
for(NSString *name in appDelegate.globalArray) 
{ 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init]; 
    NSRange r = [name rangeOfString:searchText]; 
    if(r.location != NSNotFound) 
    { 
     if(r.location== 0)//that is we are checking only the start of the names. 
     { 
      [tableData addObject:name]; 
     } 
    } 
    counter++; 
    [pool release]; 
} 
[myTableView reloadData]; 
} 

你可以看到代碼「for(NSString * name in appDelegate.globalArray)」它不起作用,因爲我用這個全局數組內的數組元素填充表視圖,我做了一個例子

在我的一排表視圖有一個uitableviewcell,裏面有四個標籤; 我寫這些標籤與此globalArray的字符串,但以這樣的方式

[cell.label1 setText:[[appDelegate.globalArray objectAtIndex:indexPath.row]objectAtIndex:1]]; 
[cell.label2 setText:[[appDelegate.globalArray objectAtIndex:indexPath.row]objectAtIndex:2]]; 
[cell.label3 setText:[[appDelegate.globalArray objectAtIndex:indexPath.row]objectAtIndex:3]]; 
[cell.label4 setText:[[appDelegate.globalArray objectAtIndex:indexPath.row]objectAtIndex:4]]; 

然後在搜索欄委託方法的代碼「的(在appDelegate.globalArray的NSString *名稱)」不工作,我怎樣才能改變我的代碼?

* *我就不多說了,我想只檢查LABEL1的搜索

回答

0

這裏的問題是,globalArray是一個數組的數組。所以循環應該是這樣的。

for(NSArray *rowArray in appDelegate.globalArray) 
{ 
    for (NSString *name in rowArray) { 
     // Do your processing here.. 
    } 
} 

使用tableData

在你tableView:cellForRowAtIndexPath:,做到這一點

[cell.label1 setText:[[tableData objectAtIndex:indexPath.row]objectAtIndex:1]]; 
[cell.label2 setText:[[tableData objectAtIndex:indexPath.row]objectAtIndex:2]]; 
[cell.label3 setText:[[tableData objectAtIndex:indexPath.row]objectAtIndex:3]]; 
[cell.label4 setText:[[tableData objectAtIndex:indexPath.row]objectAtIndex:4]]; 

在你numberOfSectionsInTableView:return 1;

在你tableView:numberOfRowsInSection:return [tableData count];

你應該包括將在用戶停止搜索的搜索數據恢復到初始的內容的方法。

- (void)resetSearchData { 
    // Get appDelegate first. 

    self.tableData = [NSArray arrayWithArray:appDelegate.globalArray]; 
} 
+0

現在沒有任何問題,但不搜索,當我寫的內部搜索欄的名稱,內容留在泰伯維 – CrazyDev 2011-05-30 09:01:50

+0

同樣在這裏有兩件事情 - '[資料表ADDOBJECT:名字]'應該是'[資料表ADDOBJECT: rowArray];'你應該在'tableView:cellForRowAtIndexPath:'方法中用'tableData'替換'appDelegate.globalArray'。 – 2011-05-30 09:04:29

+0

第一件事就行了;第二件事我在loadview中做到這一點:[tableData addObjectsFromArray:appDelegate.globalArray]; – CrazyDev 2011-05-30 09:11:28