1
var arr = defaults.arrayForKey("kWeeks") as [WeekReport]?
if arr? {
    var arr2 = arr!
    arr2.append(report)
    defaults.setObject(arr2, forKey: "kWeeks")           // Crash
    defaults.synchronize()
}

I try to set arr2 which will be the add after optional checking. But it crashes on setObject() with error: EXC_BAD_ACCESS

Ive checked, with println() and arr2 is not nil and contains the element which is appended in the sample above. And report is of type WeekReport.

Arbitur
  • 38,684
  • 22
  • 91
  • 128

1 Answers1

0
var arr = defaults.arrayForKey("kWeeks") as [WeekReport]?

Is doing a forced casting to an optional array of WeekReport. Instead, you really want to do an optional casting:

if let arr = defaults.arrayForKey("kWeeks") as? [WeekReport] {
    arr.append(report)
    defaults.setObject(arr, forKey: "kWeeks")
    defaults.synchronize()
}

This says, "if there is an array for "kWeeks" that can be cast to an array of WeekReport, do the following with it as arr"

You also need to make sure that WeekReport inherits from the NSCoding protocol so that it can be converted to data.

drewag
  • 93,393
  • 28
  • 139
  • 128