0

I am trying to access all the first name value field from the address book. I am using this code for this

CFStringRef firstName = ABRecordCopyValue(aSource, kABPersonFirstNameProperty);
first_name=[NSString stringWithFormat:@"%@",firstName];
CFRealease(firstname)

I am not using ARC. So i need to CFRealease(firstname) at the end. But in my code when i add CFRealease(firstname) my app crashes at this point and without this the app works fine.

But when i try to analyse my app by using analyzer it says object Leaked: object allocated and stored into 'firstname' is not refrenced later in the execution path and has a retain count of +1.

Case is same for midname and last name whose code are given below.

 CFStringRef midname = ABRecordCopyValue(aSource, kABPersonMiddleNameProperty);
 mid_name=[NSString stringWithFormat:@"%@",midname];
 CFRelease(midname);

 CFStringRef lastName = ABRecordCopyValue(aSource, kABPersonLastNameProperty);
 last_name=[NSString stringWithFormat:@"%@",lastName];
 CFRelease(lastName);

Please tell where i am doing it wrong. Thanks in advance.

4

1 回答 1

0

假设您将对名字的引用存储在firstname(not firstName) 中,当您尝试释放 if firstnameis引用的对象时,您的应用程序将崩溃nil。如果您的应用程序无权访问地址簿(联系人数据库),则可能会发生这种情况,因为用户尚未授予对它的访问权限。这必须在 iOS 6 中声明。在这种情况下,不会返回任何联系人。
您可以请求访问,例如使用以下代码:

-(bool)userGrantedReadAccessToContacts
{
    __block BOOL accessGranted = NO;
    if (ABAddressBookRequestAccessWithCompletion != NULL) { // iOS 6
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        ABAddressBookRequestAccessWithCompletion(contactsRef, ^(bool granted, CFErrorRef error) {
            accessGranted = granted;
            dispatch_semaphore_signal(sema);
        });
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    }
    else { // iOS 5 or earlier
        accessGranted = YES;
    }

    return accessGranted;
}
于 2013-05-27T11:46:43.147 回答