如果textField
包含任何文本,这样可以正常工作。但是如果textField
为空,则不添加任何对象。
如何告诉这段代码,如果textField
为空,所有对象应添加到resultObjectsArray
?
resultObjectsArray = [NSMutableArray array];
for(NSDictionary *object in allObjectsArray)
{
NSString *nameString = [NSString stringWithFormat:@"%@", [textField text]];
NSString *wineName = [wine objectForKey:@"Name"];
NSRange range = [wineName rangeOfString:nameString options:NSCaseInsensitiveSearch];
if ((range.location != NSNotFound))
[resultObjectsArray addObject:object];
}
答案 0 :(得分:2)
resultObjectsArray = [NSMutableArray array];
NSString *nameString = [textField text];
for(NSDictionary *object in allObjectsArray)
{
if ([nameString length] > 0)
{
NSString *wineName = [wine objectForKey:@"Name"];
NSRange range = [wineName rangeOfString:nameString options:NSCaseInsensitiveSearch];
if ((range.location != NSNotFound))
[resultObjectsArray addObject:object];
}
else
{
[resultObjectsArray addObject:object];
}
}
请注意,您不需要:
NSString *nameString = [NSString stringWithFormat:@"%@", [textField text]];
作为
NSString *nameString = [textField text];
就足够了。它也不会在for
循环内部发生变化,因此可以在它之外进行初始化。
答案 1 :(得分:0)
这就是代码最终看起来像使用@trojanfoe的答案。 (我已经排除了我的其他搜索标准)。
-(IBAction)searchButtonPressed:(id)sender{
BOOL textFieldIsEdited = NO;
if ([[textField text] length] > 0)
{
textFieldIsEdited = YES;
}
resultObjectsArray = [NSMutableArray array];
for(NSDictionary *wine in allObjectsArray)
{
BOOL nameMatch = YES;
if (textFieldIsEdited) {
NSString *wineName = [wine objectForKey:@"Name"];
NSString *nameString = [textField text];
NSRange range = [wineName rangeOfString:nameString options:NSCaseInsensitiveSearch];
if (range.location == NSNotFound) {
nameMatch = NO;
}
}
if ((nameMatch != NO))
[resultObjectsArray addObject:wine];
}