将多个变量保存到 NSUserdefaults 并按保存顺序显示在另一个视图控制器上的最佳方法是什么? [英] What's the best way to save multiple variables into NSUserdefaults and display on another view controller in the order saved?

查看:61
本文介绍了将多个变量保存到 NSUserdefaults 并按保存顺序显示在另一个视图控制器上的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新来的 swift 家伙来了!我在概念化如何存储具有多个详细信息的位置信息时遇到问题.用户默认是最好的方式吗?也许json数组文件?

New swift guy here! I'm having problems conceptualizing how to store this information of a location with multiple details. Is user defaults the best way? Perhaps json array file?

我有两个视图控制器 1. 收藏夹和 2. 信息.

I've got two view controllers 1. favorites and 2. info.

FavoritesViewController 按照收藏顺序显示多组数据

FavoritesViewController displays multiple groups of data in the order in which they were favorited like this

Favorites

Group 1             Remove button
- Name of location
- Address
- latitude
- longitude
- Hours

then continues groups

<小时>

在 infoViewController 上,它显示来自数据库的位置.它有一个收藏按钮,用于将其存储在 favoritesViewController 中.


On the infoViewController it shows locations from a database. It has a favorite button which stores it for use in the favoritesViewController.

  @IBAction func favoriteThis(_ sender: Any) { 

       // check the state of favorited button
          if toggleState == 1 {
            toggleState = 2
            favoriteThis.setTitle("favorited!", forState: .normal)
            UserDefaults.standard.set(toggleState, forKey: "favorited")

        } else {
            toggleState = 1
         favoriteThis.setTitle("favorite", forState: .normal)
            UserDefaults.standard.set(toggleState, forKey: "favorited")

        }

        //set the current values to variables

        let name = self.selectedLocation!.name
        let address = self.selectedLocation!.address
        let lat = self.selectedLocation!.latitude
        let long = self.selectedLocation!.longitude

         // set them to an array and store them with a unique id
         let array = [id, name, address, lat, long]

         let defaults = UserDefaults.standard
          defaults.set(array, forKey: "FavArray")

   }

这确实存储在 FavArray 中,但是如果我需要在 favoriteViewController 中保存和显示多个这些组,您认为解决这个问题的更好解决方案是什么?

This does store in the FavArray, but if I need to save and display more than one of these groups in favoriteViewController, What do you think is a better solution to approaching this?

谢谢大家!

推荐答案

UserDefaults 适用于小块数据.因此,我建议不要使用用户默认值,而是建议让您的自定义 PList 文件(您可以将其视为您的自定义 UserDefaults 文件)专门用于您的自定义类型数组.

UserDefaults is meant for small pieces of data. So instead of using User defaults, I would recommend making your custom PList file (You can think of it as your custom UserDefaults file) special for your array of custom Types.

为了解决您的问题,我创建了一个自定义类型,它将保存您的所有位置数据,如下所示:-

To solve your problem I created a custom Type which will hold all your location data like so: -

struct FavoriteLocation: Codable {
    let name: String
    let address: String
    let latitude:CLLocationDegrees
    let longitude: CLLocationDegrees

    init(name: String,address: String, latitude: CLLocationDegrees,longitude: CLLocationDegrees) {
        self.name = name
        self.address = address
        self.latitude = latitude
        self.longitude = longitude
    }
}

注意:您的自定义类型应符合 Codable 协议,以便可以在自定义 Plist 文件中对其进行编码和解码.

NOTE: Your Custom type should conform to Codable protocol so that it can be encoded and decoded to and from Custom Plist file.

下一个:-在您的 ViewController 中,您可以填充这种类型的数组,并使用它来保存和检索 customPList 文件中的数据.我用注释总结了 ViewController 中的所有内容,如下所示.如果您不理解其中的任何部分,请告诉我.

NEXT:- In your ViewController you can populate an array of this type and use it to save as well as retrieve data from your customPList file. I have summarized everything in a ViewController with Comments as shown below. Let me know if you don't understand any part of it.

class CustomPListViewController: UIViewController {

    /// Make your array of Favorite Locations
    let favLocationArray:[FavoriteLocation] = []

   /**
      Create our own directory to save data locally in a custom Plist file, inside our apps Document directory.
      This is used both when writing and retrieving.
     */
    let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("FavoriteLocations.plist")

    /// Save your array in custom PList file (Encode)
    func saveFavoritePLacesInCustomPList(favLocationArray: [FavoriteLocation]) {
        let encoder = PropertyListEncoder()
        do {
            let data = try encoder.encode(favLocationArray)
            guard let dataFilePath = self.dataFilePath else { return }
            do {
                try data.write(to: dataFilePath)
            } catch {
                // Handle error
            }
        } catch {
            // Handle error
        }

    }


    // Retrieve your saved data (Decode)
    func retrieveFavoriteLocations() {
        guard let filePath = self.dataFilePath else {return }
        do {
            let data = try Data(contentsOf: filePath)
            let decoder = PropertyListDecoder()
            do {
                let favoriteLocationsArray = try decoder.decode(Array<FavoriteLocation>.self, from: data)
                // This is your data ready to use
                print(favoriteLocationsArray)

            } catch  {
                // Handle error
            }

        } catch  {
           // Handle error
        }

    }



}




它是如何工作的?

我们使用PropertyListEncoderencode 即将您的自定义对象转换为可以保存在.plist 文件中的格式.并将您的数据返回到您的应用程序的模型 (FavoriteLocation),我们使用 PropertyListDecoder 做相反的事情,即 decode .plist 格式化数据返回到您的自定义对象.

We are using PropertyListEncoder to encode ie to transform your custom object into a format which can be saved in .plist file. and to get your data back to your app's model (FavoriteLocation) we use PropertyListDecoder which does the opposite ie decode .plist formatted data back to your custom Object.

如何查看您的自定义 .plist 文件?

在您的 viewDidLoad 方法调用 print(dataFilePath!)这将打印您可以导航到它的完整文件路径并查看您的 FavoriteLocations.plist

On your viewDidLoad method call print(dataFilePath!) This will print the full file path which you can naviagate to it and see your FavoriteLocations.plist

这篇关于将多个变量保存到 NSUserdefaults 并按保存顺序显示在另一个视图控制器上的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆