2015-10-26 62 views
1

我试图了解这段代码是如何导致内存泄漏,我很难。从我一直在读的内容来看,ARC不管理CF对象,我必须释放它们。我试过这样做,但根据Apple的仪器工具仍然有泄漏。任何意见将不胜感激...提前致谢内存泄漏与IOPSCopyPowerSourcesInfo()

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

回答

0

你必须释放由名称中的'创建'或'复制'函数返回的对象。所以不要释放pSource和psValue,释放blob和源代码。