【问题标题】:How to implement number comparison like in the native iPhone contacts app?如何在原生 iPhone 联系人应用程序中实现数字比较?
【发布时间】:2014-12-27 18:47:20
【问题描述】:

我想比较两个数字,例如以防万一。 number987654。 可以保存为+91 9876540987654。但是,虽然searchingcomparing,数字完全匹配并正确显示。

现在我正在使用此代码来比较确切的数字。我该如何增强它?

// Remove non numeric characters from the phone number
phoneNumber = [[phoneNumber componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]] componentsJoinedByString:@""];

NSPredicate *predicate = [NSPredicate predicateWithBlock: ^(id record, NSDictionary *bindings) {
    ABMultiValueRef phoneNumbers = ABRecordCopyValue( (__bridge ABRecordRef)record, kABPersonPhoneProperty);
    BOOL result = NO;
    for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++) {
        NSString *contactPhoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
        contactPhoneNumber = [[contactPhoneNumber componentsSeparatedByCharactersInSet:     [[NSCharacterSet alphanumericCharacterSet] invertedSet]] componentsJoinedByString:@""];
//Comparing the string are equal. phoneNumber is the number I am comparing to. 
        if ([contactPhoneNumber isEqualToString:phoneNumber])  {
            result = YES;
            break;
        }
    }
    CFRelease(phoneNumbers);
    return result;
}];

上面的代码结果是YES,只有在contactPhoneNumber和phoneNumber完全一样的情况下。 当0987654+91 987654987654 时不是。

同样的事情也适用于 WhatsApp 号码比较。 任何人都可以提供任何线索吗?

【问题讨论】:

  • 请提供有关两个数字何时相等的更多信息。从您的单个示例中,我不明白如何确定两个给定的电话号码是否相同。去除前导零,删除国家代码……请提供一个完整的数字规范化步骤列表。
  • Amol,您可能要考虑使用 Google 电话号码库 github.com/iziz/libPhoneNumber-iOS,它非常擅长解析、格式化、比较电话号码。这个库应该可以处理很多常见和晦涩的案例。

标签: ios objective-c comparison contacts phone-number


【解决方案1】:

好吧,我知道这不是最简洁的代码,但是...

NSString *originalPhoneNumber = [insert phone String];
int phoneNumber = [originalPhoneNumber intValue];
NSString *phoneFormatOne;//This will be your number formatted like 0987654
NSString *phoneFormatTwo;//This will be your number formatted like +91 987654
int phoneNumberFormatOne = [phoneFormatOne intValue];
NSString *partOne = [phoneFormatTwo substringWithRange:NSMakeRange(1,3)];
NSString *partTwo = [phoneFormatTwo substringWithRange:NSMakeRange(4,10)];
int phoneNumberFormatTwo = [partOne intValue]*1000000 + [partTwo intValue];

现在您拥有所有三个整数格式,分别称为 phoneNumber、phoneNumberFormatOne 和 phoneNumberFormatTwo。您现在可以在 if 语句中将整数与 == 进行比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-11
    • 2011-01-24
    • 2021-03-09
    • 2011-02-27
    • 1970-01-01
    • 2014-04-11
    相关资源
    最近更新 更多