September 2008 Archives

Proper Key-Value Observer Usage

|

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.

Handy NSString Conversion Macro

|

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.

About this Archive

This page is an archive of entries from September 2008 listed from newest to oldest.

August 2008 is the previous archive.

November 2008 is the next archive.

Find recent content on the main index or look in the archives to find all content.

Links

Powered by Movable Type 4.1