1

如果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];
}
4

2 回答 2

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循环内改变,因此可以在循环外初始化。

于 2012-08-21T11:48:22.480 回答
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];
}
于 2012-08-21T13:35:38.840 回答