An ActionScript developer with EXC_BAD_ACCESS? Just check your strings…

Because ActionScript is an ECMA based language, strings are declared a literals using quotes:

var string = "This is an ECMA string";
var anotherString = 'So is this';

Objective-C on the other hand, uses the class NSString for string access, and you declare a constant string using a convenience method by putting an @ in front of your quotes:

NSString *string = @"This is an NSString";

“Yeah…? So?”

Well, I spent 2 hours yesterday tracking down a dreaded EXC_BAD_ACCESS somewhere in my app – being new to Objective-C I just assumed that I’d messed up my memory management somewhere and double-released, or used an autorelease where I shouldn’t have. But I checked and checked and checked and couldn’t figure it out. I finally managed to track the crash down to a particular message call to a method that took an NSDictionary as one of it’s arguments:

[self.flickrRequest callAPIMethodWithPOST:@"" arguments:
    [NSDictionary dictionaryWithObjectsAndKeys:OBJECTIVE_FLICKR_API_KEY, @"api_key",

Whenever I sent this message, the program would crash. I checked for a memory leak in every object in my class, I even looked for memory leaks in the ObjectiveFlickr framework… But you see the issue right? Look again:

... ,@"photos","media",nil]];

It looked right to me because I’ve been an ActionScript developer for so long that anything in quotes just looks valid. And in C it is a valid character string constant (so there was no compile-error).
But if you pass a C string (rather than an NSString) as they key in an NSDictionary, you get an EXC_BAD_ACCESS. And a lot of wasted time.

... ,@"photos",@"media",nil]];

That’s better.