3

I have this NSDate extension with nullable init, which worked fine all the time, until I updated to newly released Xcode 7.3.

Now it crashes with EXC_BAD_ACCESS.

extension NSDate
{
    convenience init?(dateString:String, formatString:String?)
    {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = formatString

        let newDate:NSDate? = dateFormatter.dateFromString(dateString)

        if let newNewDate = newDate
        {
            self.init(timeInterval:0, sinceDate:newNewDate)
            return
        }

        print("ERROR: Wrong format [\(formatString)] for date [\(dateString)]")
        return nil
    }
}

let d1 = NSDate(dateString: "2016-01-01 11:00:00", formatString: "yyyy-MM-dd hh:mm:ss") // OK
let d2 = NSDate(dateString: "qq123", formatString: "qwe") // EXC_BAD_ACCESS

Do you have any possible solution for this? Cannot figure out - am I abusing extension of NSDate somehow?

Maris
  • 664
  • 1
  • 5
  • 15

1 Answers1

1

As dan mentioned in his comment already, making sure to always initialize the object before returning nil from a failable initializer (or throwing from a throwing initializer) fixes this issue.

For more information on the underlying issue, see SR-704: EXC_BAD_ACCESS on returning nil from a failable initializer of NSObject subclass. Looks like it was fixed in the mainline branch, but didn’t make it into the final Swift 2.2 release. Expect it to be fixed in the next point update.

Community
  • 1
  • 1
Ole Begemann
  • 135,006
  • 31
  • 278
  • 256