使用nspredicate检查电话号码的数组

时间:2013-10-18 05:53:52

标签: ios objective-c nspredicate

我有一系列的电话号码,我需要检查一个特定的(给定的)电话号码是否包含在该阵列中。所以我怎么能用NSPredicate来做到这一点。(NB目前我正在使用数组包含对象方法。在我的问题中我需要一个使用谓词的解决方案)。所以,如果有人知道这一点,请帮助我

 NSString *p = allUsers.phoneNumber;
            NSString *p1 = [p stringByReplacingOccurrencesOfString:@"-" withString:@""];
            NSString *p2 = [p1 stringByReplacingOccurrencesOfString:@"(" withString:@""];
            NSString *p3 = [p2 stringByReplacingOccurrencesOfString:@")" withString:@""];
            NSString *p4 = [p3 stringByReplacingOccurrencesOfString:@" " withString:@""];
            NSString *p5 = [p4 stringByReplacingOccurrencesOfString:@"+" withString:@""];
            NSString *p6 = [p5 stringByReplacingOccurrencesOfString:@"*" withString:@""];
            NSString *p7 = [p6 stringByReplacingOccurrencesOfString:@"#" withString:@""];


 if ([arrayAllPhoneNumbers containsObject:p7])
            {
                allUsers.isPhoneUser = YES;

            }

2 个答案:

答案 0 :(得分:2)

// For number kind of values:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF = %@", value];
NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];

// For string kind of values:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@", value];
NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];

// For any object kind of value (yes, you can search objects also):
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", value];
NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];

答案 1 :(得分:1)

一个好的解决方案是尽管使用NSPredicate,您可以尝试使用NSDatDetector 请尝试以下: -

NSString *p = @"8147744507";
NSError *error = NULL;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink|NSTextCheckingTypePhoneNumber
                                                           error:&error];
NSArray *matches = [detector matchesInString:p
                                     options:0
                                       range:NSMakeRange(0, [p length])];
for (NSTextCheckingResult *match in matches)
{
    if ([match resultType] == NSTextCheckingTypePhoneNumber)
    {
        NSString *phoneNumber = [match phoneNumber];
        NSLog(@"phone no valid=%@",phoneNumber);
    }
}