EXC_BAD_ACCESS on iOS 8.1 with Dictionary

i0S Swift Issue

Question or problem in the Swift programming language:

I have an object accessible via a static var in a struct (workaround for the lack of class variable support in swift right now), structured like this:

struct Constants{
    static var myObj = MyObject()

MyObject has a dictionary in it like so:

class MyObject{
    private var params = Dictionary()

    func addParam(key:String, value:AnyObject){
        params[key] = value

Now on the first call to this object for Contants.myObj.addParam(“param”, value:123) all is well and params has contents [“param”:123]. On the second call for Contants.myObj.addParam(“param”, value:456), I get a EXC_BAD_ACCESS.

Here’s the kicker though, this only occurs in iOS 8.1. Also, if I add the line let stupidHack = self.params as the first line of my addParam method, it works fine. My assumption is that it deals with mutability of dictionaries. The let may somehow trigger the dictionary to be mutable again after initialization.

Has anyone else run into this issue before? Any idea on how to fix it?


How to solve the problem:

Solution 1:

Looks like a compiler bug.

Have you tried switching between Release and Debug then rebuilding? If debug works but not release it can be an indication of a compiler/optimizer bug.

Does it happen in the simulator also?

Your code works for me on iOS 8.1 with XCode 6.1.

Solution 2:

By chance, do you have an iPhone 6 with 64Gb ?
I have one and I had the same issue using Dictionaries twice.

In the news (well the tech news …), I read that the defective memory modules delivered by Toshiba for precisely this iPhone model could cause incorrect allocations in memory.

Solution 3:

Try adjusting the Swift compiler optimization level to “None” (Build Settings).

I had a similar issue with a class being deallocated for no apparent reason, it is mostly a compiler bug like Lee said.

Solution 4:

Faced similar kind of issues with swift code and fixed such issues by disabling swift compiler optimisation in the build settings of the application target.

Hope this helps!