'String' is not identical to 'AnyObject' error

六眼飞鱼酱① 提交于 2019-12-25 03:07:05

问题


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

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