我正在制作一个正在运行的应用程序,并希望有一个viewController,用户在该字段中随机显示运行提示和事实。我想查询解析objectIds,然后引用id并为标签指定tip或fact。目前我已经将Ids硬编码到应用程序中,但我希望该数组包含查询结果,代码如下:
func GetObjectID(){
ObjectIDs = ["id1","id2","id3","id4","id5","id6","id7","id8"]
RandomID = Int(arc4random_uniform(UInt32(ObjectIDs.count)))
}
func TheInfo(){
GetObjectID()
var query : PFQuery = PFQuery(className: "FactsandTips")
query.getObjectInBackgroundWithId(ObjectIDs[RandomID]){
(ObjectHolder : PFObject?, error: NSError?) -> Void in
if (error == nil) {
self.fact = ObjectHolder!.valueForKey("Fact") as? String
self.tips = ObjectHolder!.valueForKey("Tips") as? Array
if(self.tips.count > 0){
self.factLabel.text = self.fact
self.Button1.setTitle(self.tips[0], forState: UIControlState.Normal)
self.Button2.setTitle(self.tips[1], forState: UIControlState.Normal)
self.Button3.setTitle(self.tips[2], forState: UIControlState.Normal)
self.Button4.setTitle(self.tips[3], forState: UIControlState.Normal)
}
} else {
print("There is something wrong!")
}
}
}
我正在使用swift,Xcode7,并将其解析为我的后端
答案 0 :(得分:0)
下面是我用来查询Parse表,检索所有结果并将其全部添加到数组中的代码。然后我使用数组作为pickerView的源。
var query:PFQuery = PFQuery(className: "Drivers")
query.addAscendingOrder("Name")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
self.astrDrivers.append(object["Name"]! as! String)
}
}
self.pkvDriverTrack.reloadAllComponents()
} else {
print("Error: \(error) \(error!.userInfo)")
}
}
注意第self.astrDrivers.append(object["Name"]! as! String)
行。这是将每条记录的Name
列添加到我的self.astrDrivers
数组中。
如果您想检索多个列,最好的办法是创建一个自定义对象,如下所示:
class ObjectNewFact:NSObject {
var column1:String = String() // You might want to choose more descriptive variable names (I just don't know what your column names are).
var column2:Int = Int()
// etc.
}
然后,您可以使用类似
的行创建ObjectNewFact
的数组
var aFacts:[ObjectNewFact] = [ObjectNewFact]()
然后你可以修改例程以从Parse中检索数据:
var query:PFQuery = PFQuery(className: "Drivers")
query.addAscendingOrder("Name")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
var NewFact:ObjectNewFact = ObjectNewFact()
NewFact.column1 = object["Column1"] as! String
NewFact.column2 = object["Column2"] as! Int
self.aFacts.append(NewFact)
}
}
self.pkvDriverTrack.reloadAllComponents()
} else {
print("Error: \(error) \(error!.userInfo)")
}
}
现在你有一个充满事实的数组。您可能希望遵循这种自定义对象方法,因为您还可以包含事实ID或显示事实的次数(如果您正在跟踪那种事情)。它为将来的任何变化提供了更灵活的解决方案。
我希望这会有所帮助。