我在Parse类中有一些字符串我想要获取并填充一些UILabel的文本:
我在自定义类中实现了以下方法来查询这些字符串:
class Book: NSObject {
var query = PFQuery(className: "Books")
var titleString: String!
func fetchTitleString(){
query.whereKeyExists("Title")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
println("Successfully retrieved \(objects!.count) book Titles.")
// Do something with the found objects
if let objects = objects as? [String] {
for object in objects {
self.titleString = object
}
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
}
}
现在我需要填充的UILabel位于detailViewController中,当选择一个单元格时,它将被推送到collectionView:didSelectItemAtIndexPath
中的视图。这是代码:
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! MyCollectionViewCell
var books : Array<Book>!
let book = self.books[indexPath.row]
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewControllerWithIdentifier("DetailViewController") as! DetailViewController
controller.titleSelected = book.titleString
self.navigationController?.pushViewController(controller, animated: true)
println("user tapped on thumbnail # \(indexPath.row)")
}
titleSelected
字符串变量表示我的detailViewController中的UILabels文本之一。它将填充标签文本,从我的解析查询中抓取任何字符串对象..但是当我运行时它只是空白。我该怎么做或调整以实现我的目标?
更新
这是我的detailViewController:
class DetailViewController: UIViewController, ARNImageTransitionZoomable {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
var titleSelected: String!
deinit {
println("deinit DetailViewController")
}
override func viewDidLoad() {
super.viewDidLoad()
imageView.layer.cornerRadius = 3.0
imageView.clipsToBounds = true
}
override func viewWillAppear(animated: Bool) {
self.titleLabel.text = titleSelected
}
答案 0 :(得分:3)
我相信您的问题是您将PFObject作为String投射到此行的早期
if let objects = objects as? [String]
将此更改为
if let objects = objects as? [PFObject]
{
for oneObj in objects
{
var titleFromParse = oneObj["Title"] as! String
// then do whatever you want with titleFromParse
// for example insert to array: self.books.append(titleFromParse)
// reloadData() for the collectionView
}
}
而且我也不认为这条线是必要的
query.whereKeyExists("Title")
而且我相信你应该全局宣布这条线
var books: Array<book>!
<强>答案强> 从NSObject类**
中删除查询函数 func fetchTitleString()
{
let query = PFQuery(className: "Books")
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil
{
if let objects = objects as? [PFObject]
{
print("Successfully retrieved \(objects.count) book Titles.")
for oneObj in objects
{
let titleFromParse = oneObj["Title"] as! String
let SingleBook = Book()
SingleBook.titleString = titleFromParse
self.arrayOfStrings.append(SingleBook)
}
}
}
else
{
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
}