IOPSCopyPowerSourcesInfo() 内存泄漏

Memory Leak with IOPSCopyPowerSourcesInfo()

我试图了解这段代码是如何导致内存泄漏的,但我遇到了困难。根据我的阅读,ARC 不管理 CF 对象,我必须释放它们。我试过这样做,但根据 Apple 的 Instruments 工具,仍然存在泄漏。任何建议将不胜感激...提前致谢

- (void) getPowerInfo : (id) sender {

CFTypeRef blob = IOPSCopyPowerSourcesInfo();
CFArrayRef sources = IOPSCopyPowerSourcesList(blob);
CFDictionaryRef pSource = NULL;
const void *psValue;

// if there is no power source
if (CFArrayGetCount(sources) == 0) {

    NSLog(@"Number of power sources found: 0; Aborting battery monitoring");

} else { // if there is a power source

    // for each power source
    for (int i = 0 ; i < CFArrayGetCount(sources) ; i++) {

        pSource = IOPSGetPowerSourceDescription(blob, CFArrayGetValueAtIndex(sources, i));
        NSString *currentPowerState = CFDictionaryGetValue (pSource, CFSTR (kIOPSPowerSourceStateKey));

        if (!pSource) { // if source is nil

            NSLog(@"Power source is nil");

        } else if ([currentPowerState isEqualToString:@"AC Power"]) { // if source is adapter

            NSLog(@"Mac is plugged in.");

        } else { // if source is battery

            psValue = (CFStringRef)CFDictionaryGetValue(pSource, CFSTR(kIOPSNameKey));

            int curCapacity = 0;
            int maxCapacity = 0;
            int percent;

            psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSCurrentCapacityKey));
            CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &curCapacity);

            psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSMaxCapacityKey));
            CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &maxCapacity);

            percent = (int)((double)curCapacity/(double)maxCapacity * 100);

            if (!percent) {

                NSLog(@"Battery %% is nil");

            } else {

                NSLog(@"Battery %% is %i", percent);

            }

            CFRelease(psValue);

        }

    }

}

CFRelease(sources);
CFRelease(pSource); }

您必须释放名称中包含 'Create' 或 'Copy' 的函数返回的对象。所以不要释放 pSource 和 psValue,释放 blob 和 sources。