Swift将PFQuery转换为TableView的字符串数组

时间:2015-04-23 02:14:48

标签: ios uitableview swift parse-platform pfquery

我正在尝试查询数据库中的所有Parse用户,然后在tableview中显示每个用户在他们自己的单元格中。我已经设置了我的tableview,但我仍然坚持将用户查询保存到可以在tableview中使用的字符串数组。我创建了一个loadParseData函数,用于在后台查找对象,然后将查询的对象追加到字符串数组中。不幸的是,我在附加数据的行上收到了一条错误消息。

Implicit user of 'self' in closure; use 'self.' to make capture semantics explicit'在我看来,我建议使用self.代替usersArray.,因为这是在一个闭包内,但如果我运行,我会再犯一个错误就这样,*classname* does not have a member named 'append'

这是我的代码:

import UIKit

class SearchUsersRegistrationViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var userArray = [String]()

    @IBOutlet var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

    }

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


    func loadParseData(){

        var query : PFQuery = PFUser.query()

        query.findObjectsInBackgroundWithBlock {
            (objects:[AnyObject]!, error:NSError!) -> Void in

            if error != nil{

                println("\(objects.count) users are listed")

                for object in objects {

                    userArray.append(object.userArray as String)

                }
            }

        }

    }


    let textCellIdentifier = "Cell"

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {

        return 1

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //return usersArray.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as SearchUsersRegistrationTableViewCell

        let row = indexPath.row

        //cell.userImage.image = UIImage(named: usersArray[row])

        //cell.usernameLabel?.text = usersArray[row]

        return cell
    }


}

1 个答案:

答案 0 :(得分:0)

问题是userArray是一个NSArray。 NSArray是不可变的,意味着它无法改变。因此它没有附加功能。你想要的是一个NSMutableArray,可以更改并具有addObject函数。

var userArray:NSMutableArray = []

func loadParseData(){
    var query : PFQuery = PFUser.query()
    query.findObjectsInBackgroundWithBlock {
        (objects:[AnyObject]!, error:NSError!) -> Void in
        if error == nil {
            if let objects = objects {
                for object in objects {
                    self.userArray.addObject(object)
                }
            }
            self.tableView.reloadData()
        } else {
            println("There was an error")
        }
    }
}

另外,因为对象是以' AnyObject'你必须在某些时候将它们作为PFUsers投射,以便使用它们。请记住一些事情

获取用户的用户名并显示

//将它放在cellForRowAtIndexPath

var user = userArray[indexPath.row] as! PFUser
var username = user.username as! String
cell.usernameLabel.text = username