pasqui86
pasqui86

Reputation: 529

objective c find contact in addressbook by phone number

like title what is the best and efficient way to find a contact in device addressbook by phone number? Actually i use a method like this:

Note that:
[rm getElencoContatti] returns all contacts in addressbook
[contatto getID] returns contacts id from addressbook
[contatto getNumeriContatto] returns all contacts' phone number from addressbook

+(NSMutableDictionary *)getNomeContattoDaNumero:(NSString *)numeroTelefono {

    NSMutableDictionary *returnValue = [[NSMutableDictionary alloc]init];
    NSNumber *idContact;

    for(ContattoRubrica *contatto in [rm getElencoContatti]) {
        idContact = [contatto getID];
        for(id numero in [contatto getNumeriContatto]) {

            if([numeroTelefono isEqualToString:[numero objectForKey:@"numeroTelefono"]]) {

                [returnValue setValue:[contatto getNomeContatto] forKey:@"nome"];
                [returnValue setValue:idContact forKey:@"idContatto"];

                return returnValue;
            }
        }
    }

    [returnValue setValue:numeroTelefono forKey:@"nome"];
    [returnValue setValue:[NSNumber numberWithInt:-1] forKey:@"idContatto"];

    return returnValue;

}

I tested this method with addressbook of about 200 contact, and this function is very slowly. Exist any ABAddressbook.h method that do this automatically ?

Thanks in advance.

Upvotes: 2

Views: 1927

Answers (1)

warrenm
warrenm

Reputation: 31782

ABAddressBook on iOS provides fewer search facilities than the equivalent API on Mac OS. Unfortunately, filtering contacts will require a linear scan, such as the one you've shown above. Apple's documentation includes a slightly different approach using block-based predicates, but it's fundamentally equivalent to what you're doing here.

One possible speed-up would be to avoid constructing all of your ContattoRubrica objects until after you've performed the search and found (or not found) the matching ABPerson records. In any case, you should use Instruments to determine where your code is spending most of its time.

Upvotes: 2

Related Questions