我正在尝试获取拥有玻璃柜的客户的姓名。
这是我的代码。
为了保存数据,我这样做:
self.vitrine["username"] = PFUser.currentUser()?.username
self.vitrine["name"] = nameTextField.text as String
var relation = self.vitrine.relationForKey("client")
relation.addObject(self.client)
self.vitrine.saveEventually { (success, error) -> Void in
if(error == nil){
}else{
println(error?.userInfo)
}
self.fetchAllVitrines()
self.navigationController?.popToRootViewControllerAnimated(true)
}
}
而且它有效。在解析中我可以看到这种关系正在起作用。
我正在尝试访问这样做的关系数据:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("vitrineCell", forIndexPath: indexPath) as! VitrineTableViewCell
var object: PFObject = self.vitrineObjects.objectAtIndex(indexPath.row) as! PFObject
cell.nomeLabel.text = object["name"] as? String
let x: PFRelation = object["client"] as! PFRelation
// cell.clientNameTextView.text = object["client"]["name"] as String
return cell
}
但是当我在客户端列中记录数据时,我看到的是:
<PFRelation: 0x7b7f1390, 0x7b7cfdc0.client -> Client>
请有人帮助我。我已经坚持了2天了Parse Doc 我读了超过 3 遍。但我找不到办法做到这一点。
问候, 迪奥戈·阿马拉尔
<小时/>好吧,我添加代码:
query!.getFirstObjectInBackgroundWithBlock {
(object: PFObject?, error: NSError?) -> Void in
if error != nil || object == nil {
println("The getFirstObject request failed.")
} else {
println(object)
cell.clientNameTextView.text = object["name"] as? String
}
}
但是这一行:cell.clientNameTextView.text = object["name"] as? String
给我一个错误。 “无法分配“字符串”类型的值?为“String!”类型的值...
我已经尝试过:
cell.clientNameTextView.text = object["name"] as! String
cell.clientNameTextView.text = object["name"] as String
cell.clientNameTextView.text = object["name"] as? String
我该如何解决这个问题?
最佳答案
如果您使用关系(而不是指针),那么您需要注意关系存储其目标对象的数组。所以,当你执行
var relation = self.vitrine.relationForKey("client")
relation.addObject(self.client)
您正在将 self.client
添加到 client
数组中。如果一个玻璃柜只能有一个所有者,并且应该将其存储在客户端字段中,那么您可能需要使用指针而不是关系。
由于这个数组,您编写的代码将无法工作。您需要从您的 vitrine 对象中获取关系,查询它,从您想要的数组中提取元素,然后您就可以使用它。
let x: PFRelation = object["client"] as! PFRelation
let query = x.query()
// Lets say that you are only interested in the first element in your array...
query.getFirstObjectInBackgroundWithBlock { first, error in
// Should do error checking here
cell.clientNameTextView.text = first!.objectForKey("name") as? String
}
这个方法效率也有点低。您应该使用某种形式的缓存,或者理想情况下,确定您是否确实需要使用关系或指针是否足够。如果指针可以,您还可以在通过 PFQuery
上的 includeKey
方法运行原始查询时包含它指向的数据。您不能在关系上使用 includeKey
。
关于ios - 无法访问 PFRelation 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31526420/