Friday, February 20, 2009

Cross Development Hint

I'm back to writing some Cocoa code after doing nothing but iPhone work for almost a year (March last year until now). It's a nice change, and in a way, the similarities between the two almost make it harder for my brain to switch gears. I keep trying to use UIxxxxxx instead of NSxxxxxx.

Anyway, there may be times when you want to share code between a Mac and an iPhone program, and for the most part, that's not going to be a problem. However, there are a few gotchas.

First and foremost, if you're using Garbage Collection on the Mac (and you really should be at this point, and at worst you should make the switch when you move to Snow Leopard), how do you define your properties so that they work in both environments? Here's one way. Somewhere in a header file that all of your files will #import, add this:

#ifdef TARGET_OS_IPHONE
#define ASSIGN_OR_RETAIN retain
#else
#define ASSIGN_OR_RETAIN assign
#endif

Now, when you go to declare your properties, do it like so:

@property (nonatomic, ASSIGN_OR_RETAIN) NSString *name;

Your properties will be defined properly in both environments. Make sure you've enabled GC on the Mac target, however, or you'll have problems. GC is still opt-in at this point. If you're not going to use GC, then there's no need to do this.

No comments:

Post a Comment