2015-10-26 109 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和源代碼。