从Parse.com获取数据作为变量

时间:2014-11-22 20:49:29

标签: ios swift parse-platform

我对iPhone的编程很新,并且经常关注几个教程并且经常使用这个网站(我必须对此给予我很大的支持,我真的希望我能够贡献并帮助其他人。)

我目前有一个快速的应用程序,它将数据插入Parse.com,并将其重新检索并显示在NSLog中。

这是AppDelegate.swift文件中的代码:

Parse.setApplicationId("xxxx", clientKey: "xxxx")   

    var gameScore = PFObject(className: "GameScore")
    gameScore.setObject(1337, forKey: "score")
    gameScore.setObject("Sean Plott", forKey: "playerName")
    gameScore.saveInBackgroundWithBlock {
        (success: Bool!, error: NSError!) -> Void in
        if (success ?? false) {
            NSLog("Object created with id: \(gameScore.objectId)")

        } else {
            NSLog("%@", error)
        }
    }

    var query = PFQuery(className: "GameScore")
    query.getObjectInBackgroundWithId("phNzKk6364") {

        (scoreAgain: PFObject!, error: NSError!) -> Void in

        if error == nil {
            NSLog("No Error: %@", scoreAgain.objectForKey("playerName") as NSString)

        } else {
            NSLog("%@", error)
        }
    }

正如您在这些代码行中所看到的,该特定用户的值已被占用并放置在NSLog中。如何将其分配给变量并将其传递给UILabel。

我创建了一个ViewController的实例,如下所示:

let vcObj : ViewController = ViewController() 

并尝试在输出它的NSLog下添加它。

self.vcObj.playerName.text = scoreAgain.objectForKey("playerName")

但是我收到了这个错误

fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb) 

有人可以帮助我从Parse.com获取变量,将其分配给变量然后将其传递给ViewController标签吗?

由于

1 个答案:

答案 0 :(得分:0)

问题是故事板正在为您创建ViewController,然后您正在分配第二个。你的不在屏幕上,因为你的自己没有从故事板上加载,你的IBOutletnil

Parse.setApplicationId("xxxx", clientKey: "xxxx")保留在AppDelegate.swift,但将其余代码移至viewDidLoad中的ViewController.swift。然后,您就可以设置自己的标签,因为IBOutlet不会nil

ViewController.swift 文件中:

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var playerName: UITextField!

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

        var gameScore = PFObject(className: "GameScore")
        gameScore.setObject(1337, forKey: "score")
        gameScore.setObject("Sean Plott", forKey: "playerName")
        gameScore.saveInBackgroundWithBlock {
            (success: Bool!, error: NSError!) -> Void in
            if (success ?? false) {
                println("Object created with id: \(gameScore.objectId)")
            } else {
                println(error)
            }
        }

        var query = PFQuery(className: "GameScore")

        query.getObjectInBackgroundWithId("phNzKk6364") {

            (scoreAgain: PFObject!, error: NSError!) -> Void in

            if error == nil {
                println("No Error: " + (scoreAgain.objectForKey("playerName") as String))
                self.playerName.text = scoreAgain.objectForKey("playerName") as String
            } else {
                println(error)
            }
        }
    }
}