title: EXC_BAD_ACCESS (code=2) when using NSNumberFormatter
body: <p>I'm having a problem, which I can't figure out for the life of me. I've searched the internet, trying to understand Swifts's <code>EXC_BAD_ACCESS</code>, but nothing seemed to help.</p>
  <hr />
  <p>The following code is quite long, but most of the time the comments are all the information needed to understand the item of relevance.</p>
  <p>I have a class <code>CalculatorController</code>, which contains the following relevant methods and properties:</p>
  <pre><code>import UIKit    
  
  class CalculatorController: UIViewController {
  
      // the actual `@IBOutlet` which is never accessed directly
      @IBOutlet private weak var _mainDisplay: UILabel!
      
      // an instance of `MainDisplayMicroController`
      // holds a reference to `_mainDisplay`
      // is used to manipulate `_mainDisplay` in a controlled way
      private var mainDisplay: MainDisplayMicroController!
      
      override func viewDidLoad() {
          super.viewDidLoad()
  
          // connects `mainDisplay` with `_mainDisplay`
          mainDisplay = MainDisplayMicroController(label: _mainDisplay)
          
          // sets `_mainDisplay`'s `text` property to &quot;0&quot;
          mainDisplay.content = .Number(0)
      
          //...
      }
  
      //...
  }
  </code></pre>
  <p>In order to manage <code>_mainDisplay</code> in a certain way, I have created a class <code>MainDisplayMicroController</code>, which on the one hand contains a reference to the the <code>UILabel</code> itself, and on the other hand contains methods and properties, which perform actions on the <code>UILabel</code>:</p>
  <pre><code>import UIKit
  
  class MainDisplayMicroController {
      
      // used to express what `label.text` is currently showing
      private enum DisplayState {
          case ShowingNumber
          case ShowingConstant
          case ShowingErrorMessage
          case Unknown
      }
  
      // holds the current state of what `label.text` is showing
      private var state = DisplayState.Unknown
  
      // used to pass different types of values in and out of this class
      enum ContentType {
          case Number(Double)
          case Constant(String)
          case ErrorMessage(String)
          case Unknown(Any?)
      }
  
      // holds the reference to the label which is being manipulated/managed
      private var label: UILabel?
  
      // makes `label`'s `text` property directly accessible, as `label` is `private`
       var text: String? {
          get {
              return label?.text
          }
          set {
              label?.text = newValue
              removeLeadingZeros()
              transformToInteger()
          }
      }
  
      // a property to allow controlled retrieval and manipulation of `label.text`
      // uses `ContentType` to make clear what the information in `label.text` is/ is supposed to be
      var content: ContentType {
          get {
              switch state {
              case .ShowingNumber:
                  if let string = text {
                      if let value = NSNumberFormatter().numberFromString(string)?.doubleValue {
                          return .Number(value)
                      }
                  }
              case .ShowingConstant:
                  if let symbol = text {
                      return .Constant(symbol)
                  }
              case .ShowingErrorMessage:
                  if let message = text {
                      return .ErrorMessage(message)
                  }
              default:
                  break
              }
  
              state = .Unknown
              return .Unknown(text)
          }
          set {
              switch newValue {
              case .Number(let value):
                  text = &quot;\(value)&quot;
                  state = .ShowingNumber
                  removeLeadingZeros()
                  transformToInteger()
              case .Constant(let symbol):
                  text = symbol
                  state = .ShowingConstant
              case .ErrorMessage(let message):
                  text = message
                  state = .ShowingErrorMessage
              case .Unknown(let thing):
                  text = &quot;Error: Passed unknown value: \(thing)&quot;
                  state = .ShowingErrorMessage
              }
          }
      }
  
      // removes the &quot;.0&quot; from `label.text`, if it is a whole number
      private func transformToInteger() {
          if state == .ShowingNumber {
              switch content {
              case .Number(let value):
                  if round(value) == value {
                      var doubleString = &quot;\(value)&quot;
  
                      if doubleString.rangeOfString(&quot;e&quot;) == nil {
                          dropLast(doubleString)
                          dropLast(doubleString)
                      }
  
                      text = doubleString
                  }
              default:
                  break
              }
          }
      }
  
      // removes leading &quot;0&quot;s from `label.text` if they are redundant
      private func removeLeadingZeros() {
          if state == .ShowingNumber {
              switch content {
              case .Number(let displayedValue):
                  content = .Number(displayedValue)
              default:
                  break
              }
          }
      }
  
      //...
  }
  </code></pre>
  <hr />
  <p>Now, when I run the code I get the following error:</p>
  <p><img src="https://i.stack.imgur.com/u0ap9.png" alt="Error 1" /></p>
  <p>From what I've read on <code>EXC_BAD_ACCESS</code>, the error often occurs when trying to call methods on released objects. I've tried using <code>NSZombie</code>to check the issue, but I didn't find anything (probably due to my incompetence when using <code>NSZombie</code>).</p>
  <hr />
  <p>If I try to follow what is happening by logic, I come to following conclusion:</p>
  <ol>
  <li><code>mainDisplay</code> is set successfully in <code>viewDidLoad()</code></li>
  <li><code>mainDisplay.content</code> is called</li>
  <li>in the <code>content</code>'s setter the switch-statement executes the <code>.Number</code> case</li>
  <li><code>text</code> and <code>state</code> are successfully set</li>
  <li><code>removeLeadingZeros()</code> is called</li>
  <li>the switch-statement accesses <code>content</code>'s getter</li>
  <li>the switch-statement in <code>content</code>'s getter executes the <code>.ShowingNumber</code> case</li>
  <li>the if-statements resolve to true, finally trying to evaluate the <code>NSNumberFormatter</code> expression</li>
  <li>the <code>EXC_BAD_ACCESS</code> occurs</li>
  </ol>
  <hr />
  <p>Does anyone know why this is happening? Does it have to do with me manipulating an <code>@IBOutlet</code> in a different class?<br />
  Any help is greatly appreciated!</p>
  <hr />
  <p>Here are links to the complete <a href="http://swiftstub.com/246217299/" rel="noreferrer"><code>CalculatorController</code></a> and <a href="http://swiftstub.com/713057996/" rel="noreferrer"><code>MainDisplayMicroController</code></a>.</p>
  <hr />
  <h2>Update #1:</h2>
  <p>As @abdullah suggested I have tried directing the <code>NSNumberFormatter</code> expression in to multiple expressions. I still get the error though:</p>
  <p><img src="https://i.stack.imgur.com/TCm89.png" alt="Error 2" /></p>
  <hr />
  <h2>Update #2:</h2>
  <p>I've removed all references and external classes, to make it as simple as possible, while maintaining the same functionality.<br />
  All of the methods and properties defined in <code>MainDisplayMicroController</code> have been moved to <code>CalculatorModel</code>.<br />
  These methods and properties now access the original <code>@IBOutlet</code>, not any reference to it.</p>
  <p>But still when trying to run it I get <code>EXC_BAD_ACCESS(code=2)</code> at the same line of code.<br />
  I'm just super confused, as it can't have anything to do with weird references, or objects being released too soon anymore.</p>
  <p>Here's the complete code for the new <a href="http://swiftstub.com/255827761/" rel="noreferrer"><code>CalculatorController</code></a>.</p>
  <hr />
  <h2>Update #3:</h2>
  <p>I've removed the <code>NSNumberFormatter</code> line, by changing it to:</p>
  <p><img src="https://i.stack.imgur.com/l1kyu.png" alt="Change from NSNumberFormatter" /></p>
  <p>Now I get the following error though:</p>
  <p><img src="https://i.stack.imgur.com/GvGq2.png" alt="New Error" /></p>
  <p>I assume there's some fundamental problem with the code, so I'm scrapping it. But thanks for all the help, and attempts at figuring this out.</p>
  <hr />
  <h2>Update #4:</h2>
  <p>This is what I get when adding a breakpoint on throw for all exceptions:</p>
  <p><img src="https://i.stack.imgur.com/IUxwc.png" alt="Exception" /></p>