iOS - 在swift 3

时间:2017-03-31 15:00:05

标签: ios arrays dictionary

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

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

非常简单,我所做的是从URL下载JSON文件

//        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()

现在,在列表(这是一个字典数组)中,我拥有了我感兴趣的所有数据。但是,如果我想挑选一个值,或打印列表的全部内容,我该怎么做?

  

编辑:此外,我可以简化结构,不使用数组   字典,但更简单?

1 个答案:

答案 0 :(得分:1)

或者您可以使用存档

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")