How to join two strings for NSPredicate, ie firstname and lastname

后端 未结 3 2143
野趣味
野趣味 2021-02-19 09:29

I have a Person Object which has two NSString properties; firstName and lastName. I\'m currently using an NSPredicate like so

3条回答
  •  旧时难觅i
    2021-02-19 10:19

    Try this,

    NSString *text = @"John Smi";
    NSString *searchText = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    NSArray *array = [searchText componentsSeparatedByString:@" "];
    NSString *firstName = searchText;
    NSString *lastName = searchText;
    NSPredicate *predicate = nil;
    
    if ([array count] > 1) {
        firstName = array[0];
        lastName = array[1];
        predicate = [NSPredicate predicateWithFormat:@"(firstName CONTAINS[cd] %@ AND lastName CONTAINS[cd] %@) OR (firstName CONTAINS[cd] %@ AND lastName CONTAINS[cd] %@)", firstName, lastName, lastName, firstName];
    } else {
        predicate = [NSPredicate predicateWithFormat:@"firstName CONTAINS[cd] %@ OR lastName CONTAINS[cd] %@", firstName, lastName];
    }
    
    NSArray *filteredArray = [people filteredArrayUsingPredicate:predicate];
    NSLog(@"%@", filteredArray);
    

    Output:

    (
            {
            firstName = John;
            lastName = Smith;
        }
    )
    

    Here text represents the searched text. The advantage with the above is, even if you pass text = @"Smi Joh"; or text = @"John "; or text = @" smi"; or text = @"joh smi ";, it will still show the above output.

提交回复
热议问题