7

I'm trying to access the values from a CFDictionary. I've started by implementing code suggested in this question:

 CFTypeRef r = IOPSCopyPowerSourcesInfo();
 CFArrayRef array = IOPSCopyPowerSourcesList(r);
 CFDictionaryRef powerDic = IOPSGetPowerSourceDescription(array, r);

I have looked at the documentation plus other posts, but it's a bit beyond me how to work it.

What I really need is some example code that takes the code I already have and uses it to print a string of, for example, "Current Capacity".

Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
Eric Brotto
  • 53,471
  • 32
  • 129
  • 174

1 Answers1

15

CFDictionaryRef is "toll free bridged" with NSDictionary. This means you can cast one to the other interchangeably. In other words:

...
NSDictionary * powerDic = (NSDictionary *)IOPSGetPowerSourceDescription(array, r);
NSString * aValue = [powerDic objectForKey:@"aKey"];

If (for some reason) you need to stay at the CoreFoundation level (which isn't unheard-of), you'd use something like CFDictionaryGetValue().

Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
  • Hi Dave, Thanks so much for getting back to me so quick! I've tried implementing your code using a key from IOPSKeys.h and got a (null) response: NSDictionary * powerDic = (NSDictionary *)IOPSGetPowerSourceDescription(array, r); NSString * aValue = [powerDic objectForKey:@"Max Capacity"]; Could you be more specific as to how to make this work? Also, I find CFDictionaryGetValue() even more mysterious than NSDictionary so if you have a quick example snippet of how to use it, that would be awesome. Thanks again for everything! ;) Eric – Eric Brotto Jul 07 '10 at 16:13
  • @Eric if `aValue` is `nil`, then either the key doesn't exist in the dictionary or the dictionary itself is `nil`. As for `CFDictionaryGetValue()`, the first parameter to the function is the `CFDictionaryRef`, the second is the key, and the return value is the value. – Dave DeLong Jul 07 '10 at 16:42
  • Thanks for the help. I'm getting the impression that my Dictionary is nil for some reason. I'm going to look into it. If, offhand, you can think of any reason why this might be, I'm all ears ;) Thanks again! – Eric Brotto Jul 08 '10 at 09:45