EXC_BAD_ACCESS when initialising NSDictionary

It’s been a while since I last paid this blog any attention. Since my last post I’ve changed job, country and had a haircut.

I’ve started toying with iOS applications and came across the EXC_BAD_ACCESS error fairly early on. Googling around tells me this is a fairly common error with all manner of causes, many of which stem from a misunderstanding of the memory management required when working is obj-c on iOS devices.

I’ll start by saying that I am a novice obj-c developer and have been spoilt for many years with modern languages that include garbage collection as standard. I understand pointers and reference and scalar variables but this knowledge has never been more pertinent than now.

I was initialising an NSDictionary as in the code snippet below. Content and username are NSString objects and type is an NSInteger, and there exactly is my error.

NSDictionary *post = [NSDictionary dictionaryWithObjectsAndKeys:
                        content, @"content",
                        username, @"user",
                        type, @"type",
                        nil];

NSDictionary stores objects (id types, or pointers to an object) with another object as the key, in this example all my keys are NSString objects. The error with my code is that type is NSInteger which is a scalar type. When attempting to store the NSInteger it is being interpreted as a pointer and therefore likely to point at an invalid memory location.

So that’s my understanding of the problem, what’s the solution?

Quite simple really, instead of storing a scalar type we need to store a pointer to an object, iOS provides the class NSNumber to solve the problem. So taking this into account the above code becomes:

NSDictionary *post = [NSDictionary dictionaryWithObjectsAndKeys:
                        content, @"content",
                        username, @"user",
                        [NSNumber numberWithInt:type], @"type",
                        nil];

and our EXC_BAD_ACCESS error goes away. I can tell my experience with objc and iOS is going to be a challenging but fun one!

Building POST data manually

After spending quite a while trying to figure this out I’m posting it as a reminder in future

POST http://example.com/upload.php HTTP/1.1 
User-Agent: Photo Uploader (foobar/1.0.0) 
Content-Type: multipart/form-data; boundary=AaB03x 
Content-Length: xxxx 

--AaB03x 
Content-Disposition: form-data; name="foo" 
Content-Type: text/plain; charset=utf-8 

12345 
--AaB03x 
Content-Disposition: form-data; name="Filename" 
Content-Type: text/plain; charset=utf-8 

image1.jpg 
--AaB03x 
Content-Disposition: form-data; name="MimeType" 
Content-Type: text/plain; charset=utf-8 

image/jpeg 
--AaB03x 
Content-Disposition: form-data; name="ImageData";
filename="image1.jpg" 
Content-Type: image/jpeg 
Content-Transfer-Encoding: binary 

 
--AaB03x--