2012-04-22 86 views
0

我有一個數組中有幾個NSString元素,我也有一個視圖,我有一個搜索欄。我想開始搜索用戶在搜索字段中寫什麼每個NSString元素的子字符串。如果NSString元素包含子字符串,我想將它添加到一個新的數組。我試圖用代碼來做到這一點,它可以正常工作,但是它不斷添加對象,即使它已經適用於它們,所以任何人都有任何想法,爲什麼?我已經將代表設置爲自我。不斷搜索NSString搜索欄中的子字符串

//.h @interface class1的

@property(strong, nonatomic) NSMutableArray *allExercisesNames; 
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar; 
@property(strong, nonatomic) NSMutableArray *foo; 

@end 

//.m

@implementation class1 

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText 
{  
for(int i = 0; i < _allExercisesNames.count;i++) 
{ 
    if([[_allExercisesNames objectAtIndex:i] rangeOfString:searchBar.text].location != NSNotFound) 
    { 
     if(_foo == nil) 
     { 
      _foo = [[NSMutableArray alloc]initWithObjects:[_allExercisesNames objectAtIndex:i], nil]; 
      [self.gridView reloadData]; 

     } 
     else 
     { 
      [_foo addObject:[_allExercisesNames objectAtIndex:i]]; 
      [self.gridView reloadData]; 
     } 
    } 

} 

if([searchBar.text isEqualToString:@""] || searchBar.text==nil) 
    //![_allExercisesNames containsObject:searchBar.text 
{ 
    _foo = nil; 
    [self.gridView reloadData]; 
} 
} 
+0

你確定該方法被調用?你有沒有嘗試在方法中設置斷點並查看會發生什麼? – 2012-04-22 17:20:29

+0

是的,函數被調用,我可以看到它排序,但它不斷添加到foo數組,所以它在視圖中看到它的幾個元素 – 2012-04-22 17:24:51

回答

1

你沒有指定 '零' 在函數的頂部_Foo,所以它繼續增加每次鍵入內容時都會返回舊的_foo數組。

相反,您應該將_foo設置爲函數頂部的新數組,以便在掃描_allExercisesNames數組之前將其清除。

下面是一個固定的簡化版本,它還利用'for(x in y)'使其更加簡潔。

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText 
{ 
    if([searchBar.text isEqualToString:@""] || searchBar.text==nil) 
     _foo = nil; 
    else 
    { 
     _foo = [NSMutableArray new]; 
     for(NSString *exercise in _allExercisesNames) 
      if([exercise rangeOfString:searchBar.text].location != NSNotFound) 
       [_foo addObject:exercise]; 
    } 

    [self.gridView reloadData]; 
} 
+0

完美的工作,謝謝:) – 2012-04-22 17:41:23

+0

有一個問題雖然發生。比方說,如果我搜索一個子字符串,數組中沒有元素的範圍,那麼數組中的所有元素都會再次顯示。任何想法如何防止呢?我想只顯示陣列中沒有元素。 – 2012-04-22 18:46:23