Saving an array of NSURL to NSUserDefaults

女生的网名这么多〃 提交于 2019-12-14 03:57:21

问题


I have an array of NSURL items like this:

var array = [NSURL]()

I'm trying to save this to NSUserDefaults:

let defaults = NSUserDefaults(suiteName: "group.a.project")
defaults?.setObject(array, forKey: "NSURLarray")

Will result in it crashing as NSURL can't be stored in NSUserDefaults.

How can I save this array of NSURL's to NSUserDefaults, so that I can then access it and use the NSURL's in the array as required (saving an array of strings and then trying to use them as NSURL's will result in an error from xcode)?


回答1:


when saving, save the absolute strings of the urls. when loading use NSURL(URLString:) to make the strings into urls again

import UIKit

class ViewController: UIViewController {
    var urlsArray : [NSURL]?

    func load () {
        var urls : [NSURL] = []

        let stringsArray = NSUserDefaults.standardUserDefaults().objectForKey("stringsArray") as [String]?

        if let array = stringsArray {
            for string in array {
                var url = NSURL(string: string)
                urls.append(url!) //no null check
            }
        }

        self.urlsArray = urls
    }

    func save () {
        var strings : [String] = []

        if let array = self.urlsArray {
            for url in array {
                var string = url.absoluteString
                strings.append(string!) ////no null check
            }
        }

        NSUserDefaults.standardUserDefaults().setObject(strings, forKey: "stringsArray")
    }


}

saving can be reduced with KVC.

    func save () {
        var strings : [String] = []

        if let array = self.urlsArray as NSArray? {
            strings = array.valueForKeyPath("absoluteStrings")
        }

        NSUserDefaults.standardUserDefaults().setObject(strings, forKey: "stringsArray")
    }



回答2:


You could archive your URL array to an instance of NSData and store that in user defaults. To save:

let urls = [ NSURL(string: "http://www.google.com")!, NSURL(string: "http://www.stackoverflow.com")! ]
let defaults = NSUserDefaults(suiteName: "group.a.project")
let data = NSKeyedArchiver.archivedDataWithRootObject(urls)

defaults?.setValue(data, forKey: "myUrls")

To load:

if let data = defaults?.valueForKey("myUrls") as? NSData {
  if let urlsArray = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [NSURL] {
    println(urlsArray)
  }
}


来源:https://stackoverflow.com/questions/28912787/saving-an-array-of-nsurl-to-nsuserdefaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!