Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EXC_BAD_ACCESS when updating Swift dictionary after using it for evaluate NSExpression

I'm using a dictionary to evaluate an expression, when the expression has variables and the dictionary is actually used by NSExpression, something happens and I get EXC_BAD_ACCESS when trying to update the dictionary, this only happens when debugging in an iPhone6, not in the simulator and not in an iPhone 4S.

    let strExpression = "a+b+20"
    let exp = NSExpression(format:strExpression)
    self.dictionary = ["a":10.0, "b":15.0, "c":25.0]
    let value:AnyObject = exp.expressionValueWithObject(self.dictionary, context: nil)
    let doubleValue = value as Double
    self.dictionary.updateValue(doubleValue, forKey: "c")    

Something really weird is that if i add this line just after creating the dictionary, then it woks fine:

let newDic = self.dictionary    

I,m using iOS 8.1. Thanks in advance!

like image 279
juanelomx Avatar asked Nov 06 '14 18:11

juanelomx


1 Answers

With @bensarz comment, I thought it might be helpful for others searching for answers if I put the response into an actual answer instead of a comment.

Per @LeeWhitney's response on a similar post:

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: The issue seems to be solved by changing the 'Optimization Level' under the 'Swift Compiler - Code Generation' to 'None'. The issue seems to be with the 'Fastest' Compiler optimization level.

Also, a work around that I've found original before the compiler change:

If you use a let statement prior to assigning values in the dictionary, it seems to alleviate the issue. More information found at link below:

EXC_BAD_ACCESS on iOS 8.1 with Dictionary

like image 146
steventnorris Avatar answered Oct 13 '22 05:10

steventnorris