简体   繁体   English

Swift - 将字典数组保存到NSUserDefaults中

[英]Swift - Save Array of dictionaries into NSUserDefaults

I have an empty cart array -> var cart: [Dictionary<String, Any>] = [] 我有一个空的购物车数组 - > var cart: [Dictionary<String, Any>] = []

And I have 2 screens, productsView and resumeView. 我有2个屏幕,productsView和resumeView。 Into the products view I have some products. 进入产品视图我有一些产品。 When the user taps on a product, this goes to the the cart: 当用户点击产品时,会转到购物车:

cart = [[name: "A", price: "1", qty: "1"]]

If the user taps on more products: 如果用户点击更多产品:

cart = [[name: "A", price: "1", qty: "3"],[name: "B", price: "2", qty: "1"]]

Now, when the user has finished adding products to the cart, I want to show the second view with the products list, and the user can make changes to the products "qty" or delete products. 现在,当用户将产品添加到购物车时,我想显示带有产品列表的第二个视图,用户可以更改产品“qty”或删除产品。 If the user taps on back and goes to the first screen, I want to show the updated list. 如果用户点击并转到第一个屏幕,我想显示更新的列表。

I want to use NSUserDefaults to save my array and show the updated data between screens. 我想使用NSUserDefaults保存我的数组并在屏幕之间显示更新的数据。 But I'm getting the next error: 但是我得到了下一个错误:

Type '[Dictionary<String, Any>]' does not conform to protocol 'AnyObject'

edit/update: in Swift 3 your dictionary type would be ok. 编辑/更新:在Swift 3中你的字典类型可以。

Dictionaries 字典

Swift also bridges between the Dictionary type and the NSDictionary class. Swift还在Dictionary类型和NSDictionary类之间架起了桥梁。 When you bridge from an NSDictionary object with parameterized types to a Swift dictionary, the resulting dictionary is of type [Key: Value]. 当您从具有参数化类型的NSDictionary对象桥接到Swift字典时,生成的字典的类型为[Key:Value]。 If an NSDictionary object does not specify parameterized types, it is bridged to a Swift dictionary of type [AnyHashable: Any] 如果NSDictionary对象未指定参数化类型,则它将桥接到类型为[AnyHashable:Any]的Swift字典

So declaring your array of dictionaries as [[String: Any]] in Swift 3 would be fine: 因此在Swift 3中将你的字典数组声明为[[String: Any]]会很好:


Xcode 8 • Swift 3 Xcode 8•Swift 3

var cart: [[String: Any]] = []
cart.append(["name": "A", "price": 19.99, "qty": 1])
cart.append(["name": "B", "price": 4.99, "qty": 2])

UserDefaults.standard.set(cart, forKey: "myCart")

if let loadedCart = UserDefaults.standard.array(forKey: "myCart") as? [[String: Any]] {
    print(loadedCart)  // [[price: 19.99, qty: 1, name: A], [price: 4.99, qty: 2, name: B]]"
    for item in loadedCart {
        print(item["name"]  as! String)    // A, B
        print(item["price"] as! Double)    // 19.99, 4.99
        print(item["qty"]   as! Int)       // 1, 2
    }
}


You just need to change the way you are declaring your array of dictionaries. 您只需要更改声明字典数组的方式。 You should use [String: AnyObject] instead of [String: Any] . 您应该使用[String: AnyObject]而不是[String: Any] You should do as follow: 你应该这样做:

Swift 2.3 斯威夫特2.3

var cart: [[String: AnyObject]] = []
cart.append(["name": "A", "price": 19.99, "qty": 1])
cart.append(["name": "B", "price": 4.99, "qty": 2])

NSUserDefaults().setObject(cart, forKey: "myCart")

if let loadedCart = NSUserDefaults().arrayForKey("myCart") as? [[String: AnyObject]] {
    print(loadedCart)  // [[price: 19.99, qty: 1, name: A], [price: 4.99, qty: 2, name: B]]"

    for item in loadedCart {
        print(item["name"] as! String)  // A, B
        print(item["price"] as! Double) // 19.99, 4.99
        print(item["qty"] as! Int)      // 1, 2
    }
}

You are using Any which does not conform to AnyObject. 您使用的Any不符合AnyObject。 Use AnyObject for declaring your dictionary, 使用AnyObject声明您的字典,

var cart: [Dictionary<String, AnyObject>] = [["name": "A", "price": "1", "qty": "3"],["name": "B", "price": "2", "qty": "1"]]

This is beacause you are trying to store an array as "AnyObject". 这是因为您尝试将数组存储为“AnyObject”。

What you need to do is: 你需要做的是:

var counter = 0
for c in cart
{
      userDefaults.setObject(c, forKey: "cart\(counter)")
      counter++
}

You can then access your dictionary like this: 然后,您可以像这样访问您的字典:

let yourCartZero = userDefaults.objectForKey("cart0")

If you want to store the whole array at the same time: 如果要同时存储整个数组:

Then you can use this: 然后你可以使用这个:

var saving: Dictionary<String, [Dictionary<String, Any>]>

var cart: [Dictionary<String, Any>] = []

var savingCart: Dictionary<String, [Dictionary<String, Any>]> = ["savedCard" : cart]

userDefaults.setObject(savingCart, forKey: "Carts")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM