如何在swift中使用NSUserDefaults保存字符串数组

时间:2015-07-23 04:51:40

标签: ios swift nsstring nsuserdefaults swift-array

我正在尝试使用带有swift的NSUserDefaults保存字符串数组。我搜索过并相信我必须使用[NSString]而不是[String]但是应用程序仍然会崩溃并出现错误

  

致命错误:在解包可选值时意外发现nil

我看不出我做错了什么,因为它正在完美地保存整数和字符串。这是我的数据单例和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()
    }
  }
}

2 个答案:

答案 0 :(得分:2)

-(int)isNetworkType
{

    Reachability* reachability = [Reachability reachabilityForInternetConnection];

    NetworkStatus netStatus = [reachability currentReachabilityStatus];

    return netStatus;
}


-(void)checkCellularNetWork
{

    if ([self isNetworkType] == 2) { //via WWAN


    }
    else if(self isNetworkType] == 1){ // via WIFI

    }

}

答案 1 :(得分:1)

问题是代码:

myString = defaults.objectForKey(DefaultsKeys.myInt) as! String?
myInt = defaults.objectForKey(DefaultsKeys.myInt) as! Int?
myArray = defaults.objectForKey(DefaultsKeys.myArray) as! [NSString]?

as!表示展开可选值,这就是您的应用因错误而崩溃的原因

fatal error: unexpectedly found nil while unwrapping an Optional value

如果defaults.objectForKey(DefaultsKeys.myInt)为零,则不允许展开nil。你应该使用

myString = defaults.objectForKey(DefaultsKeys.myInt) as? String

代替。