从地址簿添加联系人时EXC_BAD_ACCESS?

时间:2010-11-13 07:24:09

标签: iphone objective-c ios4 addressbook abaddressbook

我有以下代码:

ABAddressBookRef ab;
ab = ABAddressBookCreate();
int len = (int) ABAddressBookGetPersonCount(ab);
int i;
for(i = 1; i < (len + 1); i++)
{
  ABRecordRef person = ABAddressBookGetPersonWithRecordID(ab,(ABRecordID) i);
  CFStringRef firstName, lastName;
  firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
  lastName = ABRecordCopyValue(person, kABPersonLastNameProperty);
  static char* fallback = "";
  int fbLength = strlen(fallback);
  int firstNameLength = fbLength;
  bool firstNameFallback = true;
  int lastNameLength = fbLength;
  bool lastNameFallback = true;
  if (firstName != NULL)
  {
     firstNameLength = (int) CFStringGetLength(firstName);
     firstNameFallback = false;
  }
  if (lastName != NULL)
  {
     lastNameLength = (int) CFStringGetLength(lastName);
     lastNameFallback = false;
  }
  if (firstNameLength == 0)
  {
    firstNameLength = fbLength;
    firstNameFallback = true;
  }
  if (lastNameLength == 0)
  {
    lastNameLength = fbLength;
    lastNameFallback = true;
  }
  firstNameString = malloc(sizeof(char)*(firstNameLength+1));
  lastNameString = malloc(sizeof(char)*(lastNameLength+1));
  if (firstNameFallback == true)
  {
     strcpy(firstNameString, fallback);
  }
  else
  {
     CFStringGetCString(firstName, firstNameString, 10*CFStringGetLength(firstName), kCFStringEncodingASCII);
  }
  if (lastNameFallback == true)
  {
     strcpy(lastNameString, fallback);
  }
  else
  {
     CFStringGetCString(lastName, lastNameString, 10*CFStringGetLength(lastName), kCFStringEncodingASCII);
  }


   printf("%d.\t%s %s\n", i, firstNameString, lastNameString);
   NSString *fname= [NSString stringWithFormat:@"%s",firstNameString];
   NSString *lname= [NSString stringWithFormat:@"%s",lastNameString];
  [dict setValue:fname forKey:@"fname"];
  [dict setValue:lname forKey:@"lname"];
  [self.arrname addObject:[dict copy]];

if (firstName != NULL)
{
    CFRelease(firstName);
}
if (lastName != NULL)
{
    CFRelease(lastName);
}

free(firstNameString);
free(lastNameString);

}

它第一次运作良好。

但是当我从联系人列表中删除记录,然后尝试在以下语句中添加记录我的应用程序。

firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty);

任何人都可以解决这个问题吗? 非常感谢任何想法。

1 个答案:

答案 0 :(得分:4)

无法保证有效ABRecordID1开始,到ABAddressBookGetPersonCount(addressBook)结束。 无法使用ABRecordID

来使用for循环

相反,请使用CFArray获取包含所有人的ABAddressBookCopyArrayOfAllPeople并对其进行迭代。

另一个评论是你不应该使用C字符串;大多数事情都可以使用CFStringNSString的API来完成,它支持开箱即用的Unicode。通过获取指定kCFStringEncodingASCII的C字符串,您基本上会破坏é或ü,ગુજરાતી或案例等字母。 (请注意,带有CFStringGetCString的{​​{1}}非常挑剔并删除不在ASCII中的字符;它不会为您提供字符串的UTF8表示。)有很多人的名字包含非ASCII字符。因此,请了解kCFStringEncodingASCIICFString方法。请注意,NSStringCFStringRef可以自由互换。