内存泄漏与IOPSCopyPowerSourcesInfo()

时间:2015-10-26 16:36:01

标签: objective-c memory-leaks instruments core-foundation

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

- (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); }

1 个答案:

答案 0 :(得分:0)

您必须释放由具有&#39;创建&#39;的功能返回的对象。或者&#39;复制&#39;在它的名字。所以不要发布pSource和psValue,释放blob和来源。