Posts filed under 'carbon'

CoreFoundation Considered Tricky

Update: see the comments for some true Cocoa wizardry.

Having spent the past few days mucking about with the MDItem objects which represent metadata in OS X files, I have this to say to the programmers who wrote applications before Cocoa:

Wow.

I expected working with C/Carbon objects to be tough, and it was. Wrapping my mind around const void * and other arcane bits of pointer-related code was - and still is - not easy, and at one point I began to despair of ever solving a particular problem. I then gave myself a healthy dose of perspective - what if I had to code in this every day, instead of doing work in the Cocoa/ObjC environment I love so much?

That shut me up, and before long I had the problem solved. I shall post my solution here so that others may correct me in the comments. :)

In short, what I wanted to do was this - I had an NSDictionary full of CoreFoundation objects - CFString, CFDate, CFArray, CFNumber and CFBoolean, primarily. I wanted to convert each of them to NSStrings in a particular representation - if it was a CFString I wanted it unchanged, if a CFDate I wanted it in mm-dd-yyyy format, if a CFArray I wanted it ignored, etc. If I was coding in Python I’d use isInstance(), in Ruby I’d use kind_of?, in Java I’d use instanceOf, and in Objective-C I’d use isKindOfObject: - but I hadn’t the faintest idea to do so in plain C.

I eventually, after looking through the Carbon documentation, wrote this solution:

void *obj = [attributes objectForKey: (NSString *)key]; // a void * points to any object
CFTypeID typeid = CFGetTypeID(obj); // getting the type ID of the object
if (typeid == CFNumberGetTypeID()) {
		// make it into an NSNumber
}
else if (typeid == CFStringGetTypeID()) {
		// just convert the string
}
else if (typeid == CFBooleanGetTypeID()) {
	if (CFBooleanGetValue(obj)) {
			// set a true value
	}
	else {
		// set a false value, duh.
	}
}
else if (typeid == CFDateGetTypeID()) {
	// convert to a date representation
}
else if (typeid == CFArrayGetTypeID())
{
	// don't do anything
}

Since there have to be a few Cocoa programmers out there who are as unfamiliar with C as I am, I thought I’d post it here.
I promise to write more entries soon; I’ve got a bad case of the blogger’s block.


2 comments January 24, 2007


About Me



I'm a college freshman, passionate about technology, programming (especially Cocoa and Python), and Apple.

By the way, 'important shock' is an anagram for 'Patrick Thomson'.

Meta

Links

Categories

Top Posts

Blog Stats