0

I am importing contacts info into some textfields, but the app crashes if there are no entries for certain fields, like phone, email, etc.

Here are my textfields:

    First Name
    Middle Name
    Last Name

    Main Phone
    Mobile Phone

    Email Address

    Website

Suppose the selected contact doesnt have a second Phone number (in this case: Mobile Phone) or there are no URL entries for the contact. The app crashes.

*ABMutableMultiValueRef phoneMulti = ABRecordCopyValue(person, kABPersonPhoneProperty);
NSMutableArray *phones = [[NSMutableArray alloc] init];
int i;
for (i = 0; i < ABMultiValueGetCount(phoneMulti); i++) {
    NSString *aPhone = [(NSString*)ABMultiValueCopyValueAtIndex(phoneMulti, i) autorelease];        
    [phones addObject:aPhone];
}

accountPhone1TextField.text = [phones objectAtIndex:0];
accountPhone2TextField.text = [phones objectAtIndex:1];
CFRelease(phoneMulti);
[phones release];*

Or if I am trying to get an email address from the contact and it doesnt exist this will crash:

NSString *anEmail = [(NSString*)ABMultiValueCopyValueAtIndex(emailMulti, i) autorelease];
//Variable is not a CFString

***** UPDATE *****

Ended up using the following code:

ABMutableMultiValueRef emailMulti = ABRecordCopyValue(person, kABPersonEmailProperty);
NSMutableDictionary *myEmailDict = [NSMutableDictionary dictionaryWithCapacity:ABMultiValueGetCount(emailMulti)];
for (CFIndex i = 0; i < ABMultiValueGetCount(emailMulti); i++) { 
    emailLabel = ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(emailMulti, i));
    email = ABMultiValueCopyValueAtIndex(emailMulti, i); 
    [myEmailDict setObject:(NSString*)email forKey:(NSString*)emailLabel];
    CFRelease(email);
    CFRelease(emailLabel);
}
WrightsCS
  • 50,551
  • 22
  • 134
  • 186

1 Answers1

2
if (phones.count > 0) {
   accountPhone1TextField.text = [phones objectAtIndex:0];
}
if (phones.count > 1) {
   accountPhone2TextField.text = [phones objectAtIndex:1];
}
LarsJK
  • 2,196
  • 18
  • 23
  • I tried that..but NSString *anEmail = [(NSString*)ABMultiValueCopyValueAtIndex(emailMulti, i) autorelease]; crashes becuase there are no email addresses – WrightsCS Sep 10 '10 at 08:55
  • Are you using kABPersonEmailProperty? – LarsJK Sep 10 '10 at 09:54
  • 1
    yes, but for some reason, if there are no records for the Email fields...it produces a crash. – WrightsCS Sep 10 '10 at 22:34
  • 1
    Seems strange. If you encapsulate that in "for (i = 0; i < ABMultiValueGetCount(emailMulti); i++) {}", that line shouldn't even be executed if there are no email adresses.. – LarsJK Sep 11 '10 at 12:04