objective-c - 很难在哪里放置 CFRelease 调用

标签 objective-c cocoa memory-leaks

我很难把我的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;
    }
}

最佳答案

正如您可能知道的,您必须释放您“拥有”的所有对象,即所有对象 从名称中包含“Create”或“Copy”的函数返回,但仅如果调用 成功了。如果函数返回 NULL,则不得对返回值调用 CFRelease

例如,在您的代码中

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

尚不清楚是否在 if block 末尾调用 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);
}

我希望这能让您开始重写完整的分析器安全函数!

关于objective-c - 很难在哪里放置 CFRelease 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16118692/

相关文章:

objective-c - 如何向我的 Cocoa 应用程序添加 Applescript 支持?

c# - 内存泄漏检测器

c++ - 安全的 std::tr1::shared_ptr 用法

objective-c - NSURLConnection 泄漏问题

ios - 如何在代码中更新Core Data数据库中的NSManagedObjects?

iphone - 如何在 iOS 中创建邮政编码字段

objective-c - NSMutableArray - 强制数组只保存特定的对象类型

iphone - 在iPhone应用程序中按顺序显示图像

objective-c - 如何访问 NSArray 中的奇偶对象

objective-c - NSTableView 列标题中的复选框