Nic*_*ill 1 iphone cocoa-touch objective-c ios4
我在某些用户的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);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
显然这行代码的结果是:ABRecordRef ref = CFArrayGetValueAtIndex(sortedPeople,i);
有时会以NSCFType而不是ABPerson的形式返回.有关如何检查结果类型的任何想法?我试图阻止这个用户的手机崩溃.一旦我到达这一行:
ABRecordCopyValue(ref, kABPersonFirstNameProperty);
Run Code Online (Sandbox Code Playgroud)
我在这一行得到了一个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
Run Code Online (Sandbox Code Playgroud)
任何帮助将非常感激!!!
我很确定崩溃发生是因为contactCount设置错误:
因此,如果您有多个包含人员的来源,则迭代将离开sortedPeople的边界.要解决这个问题,请更换
CFIndex contactCount = ABAddressBookGetPersonCount(addressbook);
Run Code Online (Sandbox Code Playgroud)
同
CFIndex contactCount = CFArrayGetCount(sortedPeople);
Run Code Online (Sandbox Code Playgroud)