0

我正在尝试将数组中的随机值调用到我的查询中,其中显示“ objectId"EXC_BAD_INSTRUCTION" ”,但在显示的地方出现错误let votes = voteCount1["votes"] as Int。它低于我IBAction的功能addVote1

我哪里错了?我正在尝试检索我的 Parse 数据控制器中某一行中的每个变量的值(每个变量都有一个特定的 objectId)并向该行中的相应变量发送投票,但我收到了错误消息。我没有得到错误的唯一方法是,如果我专门定义 objectId 来代替query.getObjectInBackgroundWithId("objectId"). 我哪里会出错?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    var voteCount1 = PFObject(className: "VoteCount")
    voteCount1["choices"] = 2
    voteCount1["votes"] = Int()
    voteCount1["votes2"] = Int()
    voteCount1["optionName"] = String()
    voteCount1["optionName2"] = String()

    var voteCount2 = PFObject(className: "VoteCount2")
    voteCount2["choices"] = 3
    voteCount2["votes"] = Int()
    voteCount2["votes2"] = Int()
    voteCount2["votes3"] = Int()
    voteCount2["optionName"] = String()
    voteCount2["optionName2"] = String()
    voteCount2["optionName3"] = String()

    var voteCount3 = PFObject(className: "VoteCount3")
    voteCount3["choices"] = 4
    voteCount3["votes"] = Int()
    voteCount3["votes2"] = Int()
    voteCount3["votes3"] = Int()
    voteCount3["votes4"] = Int()
    voteCount3["optionName"] = String()
    voteCount3["optionName2"] = String()
    voteCount3["optionName3"] = String()
    voteCount3["optionName4"] = String()

    let array = ["BiEM17uUYT", "TtKGatVCi9"]
    let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
    let objectId = array[randomIndex]




}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBOutlet weak var pollResults1: UILabel!

@IBAction func addVote1(sender: AnyObject) {
    var query = PFQuery(className: "VoteCount")
    query.getObjectInBackgroundWithId("objectId") {
        (voteCount1: PFObject!, error: NSError!) -> Void in
        if error != nil {
            NSLog("%@", error)
        } else {
            voteCount1.incrementKey("votes")
            voteCount1.saveInBackgroundWithTarget(nil, selector: nil)
        }
        let votes = voteCount1["votes"] as Int
        let votes2 = voteCount1["votes2"] as Int
        self.pollResults1.text = "\(votes)"
        }
    }
}
4

1 回答 1

0

我看到viewDidLoad你定义了一些对象,将它们存储在局部变量中,并且它们的值随着方法结束而丢失。因此它们不会以任何方式对查询和应该在解析数据库中的数据做出贡献。

也就是说,我希望调用getObjectInBackgroundWithId返回不匹配,并且voteCount1闭包参数为零。

如果发生这种情况,您应该会看到一条错误消息打印到控制台。

因此,发生异常是因为您正在访问voteCount1包含nil. 您应该将该代码移动到else分支中:

    if error != nil {
        NSLog("%@", error)
    } else {
        voteCount1.incrementKey("votes")
        voteCount1.saveInBackgroundWithTarget(nil, selector: nil)

        let votes = voteCount1["votes"] as Int
        let votes2 = voteCount1["votes2"] as Int
        self.pollResults1.text = "\(votes)"
    }

但我认为您的代码逻辑中还有其他错误,基于我在这个答案开始时所做的考虑。

于 2014-11-20T09:57:02.857 回答