I've written a macro in Objective-C to perform a safe cast. Here's what it looks like so far:
#define SAFE_CAST(OBJECT, TYPE) ([OBJECT isKindOfClass:[TYPE class]] ? (TYPE *) OBJECT: nil)
This works really well, but it'd be nice if there was a way to store OBJECT in a variable so it didn't get called twice. For instance, using the macro as such:
NSString *str = SAFE_CAST([dictinary objectForKey:key], NSString);
results in code similar to this when the macro is expanded:
NSString *str = ([[dictinary objectForKey:key] isKindOfClass:[NSString class]] ? (NSString *) [dictinary objectForKey:key]: nil);
I'd prefer for it to work more like this:
id obj = [dictionary objectForKey:key];
NSString *str = ([obj objectForKey:key] isKindOfClass[NSString class]] ? (NSString *) obj : nil);
Thanks.