Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EXC_BAD_ACCESS on iOS 8.1 with Dictionary

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<String,AnyObject>()

    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?

Thanks!

like image 690
steventnorris Avatar asked Nov 07 '14 20:11

steventnorris


3 Answers

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.

like image 134
whitneyland Avatar answered Nov 18 '22 20:11

whitneyland


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.

like image 45
Frédéric Adda Avatar answered Nov 18 '22 19:11

Frédéric Adda


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.

like image 1
r3nar Avatar answered Nov 18 '22 21:11

r3nar