Boon
Boon

Reputation: 41500

How to store a CoreFoundation type reference in NSMutableDictionary?

How can I store a CoreFoundation type reference in NSMutableDictionary? How do I know if a particular type is CFType? (say CFString)

Upvotes: 1

Views: 833

Answers (1)

NSDestr0yer
NSDestr0yer

Reputation: 1449

Generally you must convert any primitive data type or Core Foundation object into a foundation object in order to insert it into an NSDictionary, so upon getting the value back from the dictionary, you can be assured it will be a Cocoa object.

Many of the Core Foundation objects are "toll-free bridged" with their Foundation counterpart to make it easy to convert back and forth. For example, CFStringRef and NSString, CFArrayRef and NSArray, CFDictionaryRef and NSDictionary, etc. Therefore you can simply cast a Core Foundation type to store it into an NSMutableDictionary. For example,

CFStringRef myString = CFSTR("some string");
NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] initWithObjectsAndKeys:(__bridge id)(myString), @"myKey", nil];
NSLog(@"Dictionary contains %@", mutableDictionary);
//release dictionary here if not using ARC...

For Core Foundation, All Core Foundation objects are derived from CFType. So the question about if CFStringRef is a CFTypeRef, it is. Also, only Core Foundation, CFTypes, can be inserted into a CFDictionaryRef container. If you would like to find out the type of Core Foundation object from a base CFTypeRef, you can call CFTypeGetID() on it. Then, you'd need to compare the type, for example, to check if it's a string object, you would do

CFStringRef myString = CFSTR("some string"); //say this is returned from CFDictionaryGetValue()
if (CFGetTypeID(myString) == CFStringGetTypeID())
{
    NSLog(@"CFType is a string");
}

Each Core Foundation object has it's own get type id function with the consistent naming convention. So CFDataRef would have CFDataGetTypeID() and CFDateRef would have CFDateGetTypeID().

Upvotes: 2

Related Questions