[英]'String' is not identical to 'AnyObject' error
I'm having issues when trying to pass data to my Apple Watch app through NSUserDefaults from my app. 尝试通过应用程序中的NSUserDefaults将数据传递到Apple Watch应用程序时遇到问题。 Whenever I try to retrieve the array that is stored, I am getting the error
'String' is not identical to 'AnyObject'
. 每当我尝试检索存储的数组时,都会收到错误
'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: 这是我在Apple Watch部分中得到的内容:
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? 有任何想法吗?
IMO your problem is, that you try to cast an optional value, eg IMO,您的问题是,您尝试强制转换一个可选值,例如
if let names = defaults.objectForKey("namesWatch") as? NSArray
{
tempNames = names
}
Probably this SO question is related: Swift NSUserDefaults NSArray using objectForKey . 可能与此SO问题有关: Swift NSUserDefaults使用objectForKeys设置NSArray 。
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"]
}
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.