iOS-在Swift 3中打印并存储字典数组 [英] iOS - Print and store array of dictionary in swift 3

查看:177
本文介绍了iOS-在Swift 3中打印并存储字典数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我有一系列的字典:

In my project I have an array of dictionaries:

var list = [[String: Any]] ()

很简单,我要做的是从URL下载JSON文件

Very briefly, what I do is download a JSON file from a URL

//        json parsing 2
        let url:String = "https://jsonplaceholder.typicode.com/users"
        let urlRequest = URL(string: url)
        URLSession.shared.dataTask(with: urlRequest!, completionHandler: {(data, response, error) in
            if(error != nil)
            {
                print(error.debugDescription)
            }else{
                do {
                    self.list = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
                        as! [[String: Any]]
                    OperationQueue.main.addOperation {
                        self.tableView.reloadData()
                    }
                }catch let error as NSError{
                    print(error)
                }
            }
        }).resume()

现在,在列表(包含词典的数组)中,我拥有了所有感兴趣的数据。但是,如果我想选择一个值,或者打印 list 的全部内容,该怎么办?

Now, within the list (which is an array of dictionaries) I have all the data that interest me. But if I want to pick out a single value, or print the entire contents of list how am I supposed to do?


编辑:另外,我可以简化结构,而不使用字典
的数组,而是简单一些?

also, I can simplify the structure and do not use an array of dictionaries, but something simpler?


推荐答案

或者您可以使用存档

import Foundation

class UserDataManager {

var documentsURL: NSURL?
var fileURL:NSURL?

func setFileURL(file: String) {
    documentsURL = FileManager.default.urls(for: .documentDirectory,
                                                   in: .userDomainMask)[0] as NSURL?
    fileURL = documentsURL!.appendingPathComponent(file) as NSURL?

}

func write(file: String, mDict: NSDictionary) {
    setFileURL(file: file)
    let data : NSData = NSKeyedArchiver.archivedData(withRootObject: mDict) as NSData
    if let fileAssigend = fileURL {
        data.write(to: fileAssigend as URL, atomically: true)
    }
}

func read(file: String) -> NSDictionary {
    setFileURL(file: file)

    var data:NSData?
    if let url = fileURL {
        data =  NSData(contentsOf: url as URL)
        if let result = data {
            return NSKeyedUnarchiver.unarchiveObject(with: result as Data) as! NSDictionary
        }
    }

    let dict = NSDictionary()

    return dict
}
}

并与

一起使用:

        let userDataManager = UserDataManager()
        userDataManager.write(file: "userDataDict", mDict: responseObject)

读取:

        let userDataManager = UserDataManager()
        let userDataDict = userDataManager.read(file: "userDataDict")

这篇关于iOS-在Swift 3中打印并存储字典数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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