问题
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