CodeSOD: Changing Your Type

Alex sends us some Objective-C code which… well, let's just say that the code is suspicious looking, but there's nothing clearly bad about it.

+(const char*)st:(NSArray*)a a:(int)i { @try { return ([a objectAtIndex:i]==[NSNull null])?"":[[a objectAtIndex:i]UTF8String]; } @catch (...) { return ""; } }

Alex had only this to say about the code: "What the hell is this even for?"

Now, this looks cryptic, but that's a mix of Objective-C and this developer's style. This defines a static/class method (the + symbol) which takes an NSArray and an integer parameter. Then, within a try/catch we fetch the objectAtIndex, with some null checking and a conversion to a UTF8String, returning a C-style string.

In actual use, this would be invoked like: [MyClass st:anArray a:5]. Which, aside from the terrible naming convention, this doesn't seem on its face bad. The try/catch gives us a usable behavior when i is out of bounds. It's a bad idea to use C-style strings in Objective-C (NSString would be preferred), but sometimes you need to.

So why is this code getting posted here? Let me re-post it with the comment describing its purpose:

//@try, @catch required as sometimes [a objectAtIndex:i] is an NSdictionary +(const char*)st:(NSArray*)a:(int)i { @try { return ([a objectAtIndex:i]==[NSNull null])?"":[[a objectAtIndex:i]UTF8String]; } @catch (...) { return ""; } }

Most of the time, most of the entries in the array are NSStrings. But sometimes they're NSDictionarys. Why would you do this? Now, there's nothing in NSArray that prevents this- this isn't a setup with generics or templates, the NSArray is just an array of whatever you put in it. But please just put the same kinds of things in an array, for all our sakes.

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published.