I am trying to save an string array using NSUserDefaults with swift. I have searched around and believe that i have to use [NSString] not [String] however the app still crashes with error
fatal error: unexpectedly found nil while unwrapping an Optional value
I can not see what i am doing wrong as it is working perfectly fine saving ints and strings. Here is my code for my data singleton and NSUserDefaults.
struct DefaultsKeys
{
static let myString = "myString"
static let myInt = "myInt"
static let myArray = "myArray"
}
class DataContainerSingleton
{
static let sharedDataContainer = DataContainerSingleton()
var myString: String?
var myInt: Int?
var myArray:[NSString]?
/* I have also tried:
var myArray:[NSString] = [NSString]() */
var goToBackgroundObserver: AnyObject?
init()
{
let defaults = NSUserDefaults.standardUserDefaults()
myString = defaults.objectForKey(DefaultsKeys.myString) as! String?
myInt = defaults.objectForKey(DefaultsKeys.myInt) as! Int?
myArray = defaults.objectForKey(DefaultsKeys.myArray) as! [NSString]?
goToBackgroundObserver = NSNotificationCenter.defaultCenter().addObserverForName(
UIApplicationDidEnterBackgroundNotification,
object: nil,
queue: nil)
{
(note: NSNotification!) -> Void in
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject( self.myString, forKey: DefaultsKeys.my)
defaults.setObject( self.myInt, forKey: DefaultsKeys.myInt)
defaults.setObject( self.myArray, forKey: DefaultsKeys.myArray)
defaults.synchronize()
}
}
}