如何在Userdefaults中存储NSArray?

时间:2018-06-11 09:37:09

标签: json swift userdefaults

这是我的代码

var defaultValues = UserDefaults.standard
var json = NSArray()
self.defaultValues.set(json, forKey: "BedData")

我使用此代码来存储字符串并且它完美地工作但是当我尝试存储NSArray时它给了我这个错误"尝试插入非属性列表对象"

2 个答案:

答案 0 :(得分:1)

您必须进行编码和解码,以便向/从UserDefault添加和检索数据。

@import '~@angular/material/theming';
// Plus imports for other components in your app.

// Include the common styles for Angular Material. We include this here 
so that you only
// have to load a single css file for Angular Material in your app.
// Be sure that you only ever include this mixin once!
@include mat-core();

// Define the palettes for your theme using the Material Design 
palettes available in palette.scss
// (imported above). For each palette, you can optionally specify a 
default, lighter, and darker
// hue.
$app-primary: mat-palette($mat-blue, 500);
$app-accent: mat-palette($mat-blue, 900);

// The warn palette is optional (defaults to red).
$app-warn: mat-palette($mat-red);

// Create the theme object (a Sass map containing all of the palettes).
$app-theme: mat-light-theme($app-primary, $app-accent, $app-warn);

// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each 
component
// that you are using.
@include angular-material-theme($app-theme);

答案 1 :(得分:0)

感谢回复人员但是我找到了解决方案

Let json = NSArray()

存储

let data = NSKeyedArchiver.archivedData(withRootObject: json)
            self.defaultValues.set(data, forKey: "Offline-BedData")

并检索:

if let data = self.defaultValues.object(forKey: "Offline-BedData")! as? Data {

                if let dict = NSKeyedUnarchiver.unarchiveObject(with: data) as? NSArray {
                    json = dict
                    print("json\(json)")
                    self.performSegue(withIdentifier: "BedShow", sender: Any?.self)
                }
            }