【问题标题】:Memory Leak with IOPSCopyPowerSourcesInfo()内存泄漏与 IOPSCopyPowerSourcesInfo()
【发布时间】:2016-01-25 20:40:36
【问题描述】:

我正在尝试了解此代码是如何导致内存泄漏的,但我遇到了困难。从我一直在阅读的内容来看,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); }

【问题讨论】:

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


    【解决方案1】:

    您必须释放名称中包含“创建”或“复制”的函数返回的对象。所以不要释放 pSource 和 psValue,释放 blob 和源。

    【讨论】:

      猜你喜欢
      • 2011-10-16
      • 2019-08-08
      • 2012-08-21
      • 1970-01-01
      • 2015-04-15
      • 2014-03-26
      • 2012-07-09
      • 2011-01-04
      • 2015-06-28
      相关资源
      最近更新 更多