【问题标题】:Cannot add String to Array for PFUser无法将字符串添加到 PFUser 的数组
【发布时间】:2015-08-26 21:18:26
【问题描述】:

我有一个推送到提要的按钮,我想在每次单击按钮时将提要项的名称记录在我的 PFUser 类中的数组(“itemChosen”)中:

@IBAction func buttonTapped(sender: UIButton) {

        PFUser.currentUser()!.addObject(feedItem.feedItemName, forKey: "itemChosen")
        PFUser.currentUser()!.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
            println(PFUser.currentUser()?.objectForKey("itemChosen"))
        })
}

我得到错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Operation is invalid after previous operation.'

如果我使用:

PFUser.currentUser()!.setObject(feedItem.feedItemName, forKey: "itemChosen")

我可以将名称保存为单个字符串,但我想将其附加到数组中。为什么 addObject 不起作用,我该如何解决?

【问题讨论】:

  • _User 类更适合登录和注册目的。这将是创建一个新类进行解析,然后当您准备好保存数据时,您只需将其 id 与该数据相关联。

标签: ios arrays swift parse-platform pfuser


【解决方案1】:

尝试这样做:

@IBAction func buttonTapped(sender: UIButton) {
    if PFUser.currentUser()!["itemChosen"] == nil { PFUser.currentUser()!["itemChosen"] = [String]() }
    (PFUser.currentUser()!["itemChosen"] as! NSMutableArray).addObject(feedItem.feedItemName)
    PFUser.currentUser()!.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
        println(PFUser.currentUser()?.objectForKey("itemChosen"))
    })
}

问题是PFUser.currentUser!["itemChosen"] 可以是nil

编辑:我找到了一种使用 Xcode 6 的方法:

extension PFUser {
    var param: [String] {
        get {
            if let x = self["itemChosen"] as? [String] {
                return x
            } else {
                return []
            }
        }
        set(val) {
            self["itemChosen"] = val
        }
    }
}

@IBAction func buttonTapped(sender: UIButton) {
    PFUser.currentUser()!.param.append(feedItem.feedItemName)
    PFUser.currentUser()!.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
        println(PFUser.currentUser()?.objectForKey("itemChosen"))
    })
}

【讨论】:

  • 感谢您的回答.. 我试过这个,我得到的是第 2 行的错误 'operand of postfix ! should have an optional type; type is () -> PFUser?' - 所以我删除了!,我收到以下错误 '() -> PFUser does not have a member named 'subscript''
  • @SamYoungNY 抱歉,忘记编写初始化程序。现已编辑。
  • 谢谢,但不幸的是我遇到了同样的错误
  • @SamYoungNY 终于修复了。现在使用NSMutableArray 而不是[String]
  • 您使用的是哪个版本的 Xcode?我的是 v6.3.1,我认为我得到的下一个错误可能是由于这个。点击按钮后:Could not cast value of type 'Swift._SwiftDeferredNSArray' to 'NSMutableArray'. 根据这篇文章可能与 Xcode 相关:stackoverflow.com/questions/30190848/…
猜你喜欢
  • 1970-01-01
  • 2020-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-15
  • 2011-04-03
  • 2015-02-15
  • 1970-01-01
相关资源
最近更新 更多