【问题标题】:Having hard time where to put CFRelease calls [closed]很难在哪里放置 CFRelease 调用[关闭]
【发布时间】:2013-04-13 16:15:37
【问题描述】:

我很难将我的CFRelease() 调用放在下面的代码中。如果我将 CFRelease() 放在一个括号内,它会抱怨在另一个括号中丢失。

ABMutableMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);

if (phones == nil || ABMultiValueGetCount(phones) == 0) {

    CFArrayRef linkedContacts = ABPersonCopyArrayOfAllLinkedPeople(person);
    phones = ABMultiValueCreateMutable(kABPersonPhoneProperty);

    for (int i = 0; i < CFArrayGetCount(linkedContacts); i++) {

        ABRecordRef linkedContact = CFArrayGetValueAtIndex(linkedContacts, i);
        ABMultiValueRef linkedPhones = ABRecordCopyValue(linkedContact, kABPersonPhoneProperty);

        if (linkedPhones != nil && ABMultiValueGetCount(linkedPhones) > 0) {

            for (int j = 0; j < ABMultiValueGetCount(linkedPhones); j++) {

                ABMultiValueAddValueAndLabel(phones, ABMultiValueCopyValueAtIndex(linkedPhones, j), NULL, NULL);
            }
        }
    }

    if (ABMultiValueGetCount(phones) == 0) {

        return NO;
    }
}

【问题讨论】:

    标签: objective-c cocoa memory-leaks


    【解决方案1】:

    您可能知道,您必须释放您“拥有”的所有对象,即所有对象 从名称中带有“创建”或“复制”的函数返回,但仅在调用时 成功了。如果函数返回NULL,则不能在返回值上调用CFRelease

    例如,在您的代码中

    ABMultiValueRef linkedPhones = ABRecordCopyValue(linkedContact, kABPersonPhoneProperty);
    if (linkedPhones != nil && ABMultiValueGetCount(linkedPhones) > 0) {
        // ...
    }
    

    不清楚是否在 if 块末尾调用CFRelease(linkedPhones)。 如果呼叫成功与否,最好单独检查。

    所以你的那部分代码看起来像:

    ABMultiValueRef linkedPhones = ABRecordCopyValue(linkedContact, kABPersonPhoneProperty);
    if (linkedPhones != nil) {
        for (int j = 0; j < ABMultiValueGetCount(linkedPhones); j++) {
            CFTypeRef value = ABMultiValueCopyValueAtIndex(linkedPhones, j);
            if (value != nil) {
                ABMultiValueAddValueAndLabel(phones, value, NULL, NULL);
                CFRelease(value);
            }
        }
        CFRelease(linkedPhones);
    }
    

    我希望这能让您开始重写您的完整功能 Analyzer-safe!

    【讨论】:

    • 感谢您为我指明正确的方向 :)
    • @PeterWarbo:不客气。我懒得“修复”整个功能,但如有必要,请随时询问更多信息!