1

以下代码在两年前可以正常工作。

Xcode 更新后出现“AnyObject 不是 NSArray 的子类型”错误。谁能帮我修一下?

override func viewWillAppear(_ animated: Bool) {
    if let storednoteItems : AnyObject = UserDefaults.standard.object(forKey: "noteItems") as AnyObject? {
        noteItems = []
        for i in 0 ..< storednoteItems.count += 1 {
            // the above line getting Anyobject is not a subtype of NSArray error
            noteItems.append(storednoteItems[i] as! String)
        }
    }
}
4

3 回答 3

1

你根本不应该在 Swift 中使用AnyObjectand作为值类型。NSArray而且您不应该注释编译器可以推断的类型。

UserDefaults有一个专门的方法array(forKey来获取一个数组。您的代码可以简化为

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated) // this line is important. Don't forget to call super.
    if let storednoteItems = UserDefaults.standard.array(forKey: "noteItems") as? [String] {
        noteItems = storednoteItems
    }
}

并声明noteItems

var noteItems = [String]()

如果您指定类型,则循环和循环中的任何类型转换都是不必要的。

于 2018-08-23T07:12:23.297 回答
0

您输入storednoteItemsas AnyObject,但随后您尝试调用count它,并尝试对其下标。看起来您真正想要的是storednoteItems成为一个数组,那么为什么不这样输入呢?而不是as AnyObject?,只需使用as? [String]to 键入storednoteItems为字符串数组。然后摆脱: AnyObject类型上的声明,您的数组将按照您的预期运行。

于 2018-08-23T07:08:20.013 回答
0

在较新版本中更新尝试使用此..

if let storednoteItems = UserDefaults.standard.object(forKey: "noteItems") as? [String] {
    var noteItems = [String]()
    for i in 0 ..< storednoteItems.count{
        noteItems.append(storednoteItems[i])
   }
}

使用foreach循环非常有效,只需将循环替换为以下循环即可。

for item in storednoteItems{
    noteItems.append(storednoteItems[i])
}
于 2018-08-23T07:19:09.327 回答