September 2008 Archives
One of the things I like about writing for MacTech is that it causes me to evaluate my own knowledge. When writing “The Road to Code”, I’m kinda obsessed with making sure I’m doing things the “proper” way. I figure, since I’m giving guidelines and advice to new Objective-C and OS X programmers, I don’t want to start them off on the wrong foot.
For one of my latest articles, I was writing about Key-Value Observing, or KVO. KVO allows one object to register for notifications when a key of another object changes. I was writing code to register as an observer, and I realized that I wanted to make sure I was doing it right. As it turns out, my understanding, the documentation, and some sample code had holes.
Some of the most useful functions of Foundation that are not often well known are the functions to convert from non-objects to NSString:
NSStringFromRect(), NSStringFromRange(), NSStringFromClass(), etc…
For example, to print out a the bounds of a view:
NSLog(@"Bounds: %@", NSStringFromRect([view bounds]));
For some reason, I always have trouble remembering the names of these functions. Sometimes I think NSStringWithRect, sometimes I think NSRectToString, plus, I have to remember if it’s a rectangle, point, or size.
In order to simplify this and let my brain worry about more important details, I created a single macro to replace all these functions: DDToNSString:
NSLog(@"Bounds: %@", DDToNSString([view bounds]));
This works for NSPoint, NSSize, NSRect, NSRange, Class, SEL (selectors), and BOOL (using DDNSStringFromBOOL).
If you’re curious how it works, read on. If you just want to use it, it’s part of DDFoundation version 1.0b2 1.0b3.
