【发布时间】:2012-04-22 17:13:41
【问题描述】:
我有一个包含几个 NSString 元素的数组,我还有一个视图,其中有一个搜索栏。我想开始搜索用户在搜索字段中写入的内容作为每个 NSString 元素的子字符串。如果 NSString 元素包含子字符串,我想将它添加到新数组中。我试图用代码来做到这一点,它工作正常,但它不断添加对象,即使它已经为它们添加了,所以有人知道为什么吗?我已经将委托设置为 self。
//.h @接口类1
@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];
}
}
【问题讨论】:
-
您确定正在调用该方法吗?您是否尝试过在方法中设置断点并查看会发生什么?
-
是的,该函数被调用,我可以看到它确实排序了,但是它不断添加到 foo 数组中,所以它在视图中看到了它的几个元素
标签: objective-c ios xcode search