问题
I'm having issues when trying to pass data to my Apple Watch app through NSUserDefaults from my app. Whenever I try to retrieve the array that is stored, I am getting the error 'String' is not identical to 'AnyObject'
.
I've been trying to figure out a solution but I can't work out what the issue is since I am using the same method elsewhere in my app and it works without issue.
Here is what I have in the Apple Watch part:
var defaults = NSUserDefaults(suiteName: "group.AffordIt")
tempNames = defaults?.objectForKey("namesWatch") as NSArray
tempDates = defaults?.objectForKey("datesWatch") as NSArray
tempAmounts = defaults?.objectForKey("valuesWatch") as NSArray
And the containing app part:
defaults?.setObject(names, forKey: "namesWatch")
defaults?.setObject(dates, forKey: "datesWatch")
defaults?.setObject(values, forKey: "valuesWatch")
names, dates and values are String arrays.
Any ideas?
回答1:
IMO your problem is, that you try to cast an optional value, e.g.
if let names = defaults.objectForKey("namesWatch") as? NSArray
{
tempNames = names
}
Probably this SO question is related: Swift NSUserDefaults NSArray using objectForKey.
回答2:
You need to cast the objects you are retrieving from your collection as being Strings:
defaults?.setObject(names, forKey: "namesWatch") as? String
defaults?.setObject(dates, forKey: "datesWatch") as? String
defaults?.setObject(values, forKey: "valuesWatch") as? String
回答3:
let namesStringArray = ["John","Mary"]
let datesStringArray = ["May 21, 2009, 11:10 PM"]
let doublesStringArray = ["1.5","2.2","3.3"]
if let defaults = NSUserDefaults(suiteName: "group.AffordIt") {
defaults.setObject(namesStringArray , forKey: "namesWatch")
defaults.setObject(datesStringArray, forKey: "datesWatch")
defaults.setObject(doublesStringArray, forKey: "valuesWatch")
}
let defaults = NSUserDefaults(suiteName: "group.AffordIt")
if let tempNames = defaults!.stringArrayForKey("namesWatch") {
println(tempNames) // ["John", "Mary"]
}
if let tempDates = defaults!.stringArrayForKey("datesWatch") {
println(tempDates) // ["May 21, 2009, 11:10 PM"]
}
if let tempAmounts = defaults!.stringArrayForKey("valuesWatch") {
println(tempAmounts) // ["1.5", "2.2", "3.3"]
}
来源:https://stackoverflow.com/questions/27948698/string-is-not-identical-to-anyobject-error