如果可用,将项添加到特定表视图行

时间:2016-04-23 23:37:40

标签: ios arrays swift uitableview parse-server

我正在尝试从同一类(在学校)的Parse数据库中创建用户的tableView。所有用户都必须拥有用户名,但并非所有用户都会为应用提供全名或设置个人资料图片。我使用这段代码:

let studentsQuery = PFQuery(className:"_User")
studentsQuery.whereKey("objectId", containedIn: studentsArray! as! [AnyObject])

let query2 = PFQuery.orQueryWithSubqueries([studentsQuery])

query2.findObjectsInBackgroundWithBlock {
    (results: [PFObject]?, error: NSError?) -> Void in

    if error != nil {

        // Display error in tableview

    } else if results! == [] {

        spinningActivity.hideAnimated(true)

        print("error")

    } else if results! != [] {

        if let objects = results {

            for object in objects {

                if object.objectForKey("full_name") != nil {

                    let studentName = object.objectForKey("full_name")!  as! String

                    self.studentNameResults.append(studentName)


                }

                if object.objectForKey("username") != nil {

                    let studentUsername = object.objectForKey("username")!  as! String

                    self.studentUsernameResults.append(studentUsername)

                }

                if object.objectForKey("profile_picture") != nil {

                    let studentProfilePictureFile = object.objectForKey("profile_picture") as! PFFile

                    studentProfilePictureFile.getDataInBackgroundWithBlock({ (image: NSData?, error: NSError?) in

                        if error == nil {

                            let studentProfilePicture : UIImage = UIImage(data: image!)!
                            self.studentProfilePictureResults.append(studentProfilePicture)

                        } else {

                            print("Can't get profile picture")

                            // Can't get profile picture

                        }

                        self.studentsTableView.reloadData()

                    })

                    spinningActivity.hideAnimated(true)

                } else {

                    // no image

                }

            }
        }
} else {

    spinningActivity.hideAnimated(true)

    print("error")

}
}

如果所有用户都有username,full_name和profile_picture,则此代码可以正常工作。但是,我无法弄清楚如何获得用户的tableView个用户名并仅在用户有图片时将用户的姓名或图片添加到用户的相应tableViewCell。以下是我tableView的配置方式:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return studentUsernameResults.count

}


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("studentsCell", forIndexPath: indexPath) as! StudentsInClassInformationTableViewCell

        cell.studentProfilePictureImageView.layer.cornerRadius = cell.studentProfilePictureImageView.frame.size.width / 2
        cell.studentProfilePictureImageView.clipsToBounds = true

        cell.studentProfilePictureImageView.image = studentProfilePictureResults[indexPath.row]

        cell.studentUsernameLabel.text = studentUsernameResults[indexPath.row]

        cell.studentNameLabel.text = studentNameResults[indexPath.row]


        return cell

}

studentProfilePictureResultsstudentUsernameResultsstudentNameResults来自用户图片,用户名和从Parse中提取的名称结果的数组。如果用户没有个人资料照片,我会收到错误Index is out of range。显然,这意味着有三个名称,三个用户名,只有两个图片,Xcode不知道如何配置单元格。我的问题:如何设置一个表查看用户的用户名并将他们的姓名和个人资料图片放在同一个单元格中,只有他们有一个?

1 个答案:

答案 0 :(得分:1)

尝试将不同的属性存储在不同的数组中将是一个问题,因为正如您所发现的那样,您最终会遇到特定用户没有属性的问题。您可以使用一个可选项数组,这样就可以存储nil缺少的属性,但将PFObject本身存储在一个数组中并访问{{1}中的属性要简单得多而不是拆分属性。

由于提取照片需要单独的异步操作,因此您可以单独存储它。您可以使用由用户ID索引的字典,而不是使用数组来存储检索到的照片,这会产生相同的排序问题。虽然对于大量学生来说,使用cellForRowAtIndexPath之类的内容来按照SDWebImage的要求下载照片可能会更有效率。

cellForRowAtIndexPath

其他一些指示;

  • 使用_来分隔字段名称中的单词并不是真的在iOS世界中使用; camelCase是首选,因此// these are instance properties defined at the top of your class var students: [PFObject]? var studentPhotos=[String:UIImage]() // This is in your fetch function let studentsQuery = PFUser.Query() studentsQuery.whereKey("objectId", containedIn: studentsArray! as! [AnyObject]) let query2 = PFQuery.orQueryWithSubqueries([studentsQuery]) query2.findObjectsInBackgroundWithBlock { (results: [PFObject]?, error: NSError?) -> Void in guard (error == nil) else { print(error) spinningActivity.hideAnimated(true) return } if let results = results { self.students = results for object in results { if let studentProfilePictureFile = object.objectForKey("profile_picture") as? PFFile { studentProfilePictureFile.getDataInBackgroundWithBlock({ (image: NSData?, error: NSError?) in guard (error != nil) else { print("Can't get profile picture: \(error)") return } if let studentProfilePicture = UIImage(data: image!) { self.studentPhotos[object["username"]!]=studentProfilePicture } } } spinningActivity.hideAnimated(true) self.tableview.reloadData() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.students != nil { return self.students!.count } return 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("studentsCell", forIndexPath: indexPath) as! StudentsInClassInformationTableViewCell cell.studentProfilePictureImageView.layer.cornerRadius = cell.studentProfilePictureImageView.frame.size.width / 2 cell.studentProfilePictureImageView.clipsToBounds = true let student = self.students[indexPath.row] if let studentPhoto = self.studentPhotos[student["username"]!] { cell.studentProfilePictureImageView.image = studentProfilePictureResults[indexPath.row] } else { cell.studentProfilePictureImageView.image = nil } cell.studentUsernameLabel.text = student["username"]! if let fullName = student["full_name"] { cell.studentNameLabel.text = fullName } else { cell.studentNameLabel.text = "" return cell } 而不是fullName
  • 如果你有一个full_name字段或引用对象,你的Parse查询看起来会更有效,这样你就不需要提供其他类成员的数组了。
相关问题