Article 5MX6C CodeSOD: Changing Your Type

CodeSOD: Changing Your Type

by
Remy Porter
from The Daily WTF on (#5MX6C)

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.

buildmaster-icon.png [Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how! TheDailyWtf?d=yIl2AUoC8zApH3dS9JZ0iQ
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments