我在某些用户的iPhone上遇到了崩溃,我终于找到了一个可以复制问题的人。这是代码的关键部分
ABAddressBookRef addressbook = ABAddressBookCreate();
if( addressbook )
{
//Got this via http://stackoverflow.com/questions/4641229/code-example-for-abaddressbookcopyarrayofallpeopleinsourcewithsortordering
ABRecordRef source = ABAddressBookCopyDefaultSource(addressbook);
CFArrayRef sortedPeople = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressbook, source, kABPersonSortByFirstName);
//Sort them first
if( sortedPeople )
{
CFIndex contactCount = ABAddressBookGetPersonCount(addressbook);
for( int i = 0; i<contactCount; i++ )
{
ABRecordRef ref = CFArrayGetValueAtIndex(sortedPeople, i);
NSMutableString *fName = [[[NSMutableString alloc] init] autorelease];
NSMutableString *lName = [[[NSMutableString alloc] init] autorelease];
NSMutableDictionary *identifiers = [[[NSMutableDictionary alloc]init]autorelease];
if( ref )
{
//Get the user's name first
NSLog(@"%@ is the reference", ref);
CFStringRef firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
if( firstName )
{
NSString *fn = [NSString stringWithFormat:@"%@",firstName];
if([fn hasPrefix:@"(null"])
[fName appendString:@""];
else
{
[fName appendString:[NSString stringWithFormat:@"%@", firstName]];
[fName setString:[fName stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[fName substringToIndex:1]uppercaseString]]];
}
CFRelease(firstName);
}
}
}
}
}
显然是这行代码的结果: ABRecordRef ref = CFArrayGetValueAtIndex(sortedPeople,i);
有时会以NSCFType而不是ABPerson的形式返回。有关如何检查结果类型的任何想法?我试图阻止这种情况导致用户手机崩溃。一旦我到达这一行:
ABRecordCopyValue(ref, kABPersonFirstNameProperty);
我在这一行得到了一个EXC_BAD_ACCESS。当日志文件如下所示时会发生这种情况:
2011-09-11 17:24:31.355 Holler[1345:707] <CPRecord: 0x6642fb0 ABPerson> is the reference
2011-09-11 17:24:31.358 Holler[1345:707] <CPRecord: 0x66431d0 ABPerson> is the reference
2011-09-11 17:24:31.361 Holler[1345:707] <CPRecord: 0x66433b0 ABPerson> is the reference
2011-09-11 17:24:31.365 Holler[1345:707] <CPRecord: 0x6640fd0 ABPerson> is the reference
2011-09-11 17:24:31.369 Holler[1345:707] <CPRecord: 0x6643510 ABPerson> is the reference
2011-09-11 17:24:31.372 Holler[1345:707] __NSCFType is the reference
任何帮助都将非常感谢!!!
答案 0 :(得分:7)
我很确定发生崩溃是因为contactCount设置错误:
因此,如果您的地址簿中有多个包含人员的来源,则迭代将离开sortedPeople的边界。要解决此问题,请替换
CFIndex contactCount = ABAddressBookGetPersonCount(addressbook);
与
CFIndex contactCount = CFArrayGetCount(sortedPeople);
答案 1 :(得分:0)
您可以使用ABRecordGetRecordType(ref) == kABPersonType
键入 - 检查地址簿结果,以确保它是ABPerson
,而不是ABGroup
。