2016-04-23 41 views
0

我想創建一個tableView的用戶從我的Parse數據庫是在同一類(在學校)。所有用戶都必須擁有用戶名,但並不是所有用戶都會爲其提供全名或設置個人資料圖片。我用這個代碼:添加項目到特定表格查看行如果可用

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") 

} 
} 

此代碼工作正常,如果所有的用戶都有一個用戶名,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 

} 

studentProfilePictureResultsstudentUsernameResults,並提出從解析拉到用戶的圖片,用戶名和姓名的結果陣列studentNameResults。如果用戶沒有個人資料圖片,我會收到錯誤Index is out of range。顯然,這意味着有三個名字,三個用戶名和只有兩個圖片,Xcode不知道如何配置單元格。我的問題:如何設置一個用戶的用戶名的tableView,並將他們的名字和個人資料圖片放在同一個單元格中,只要他們有一個?

+0

不要存儲單獨的數組。存儲一個PFObjects數組,我建議你使用[username(string):UIImage)字典作爲照片 – Paulw11

+0

@ Paulw11當我查詢用戶的用戶名,名字和圖片時,我得到了所有的結果曾經,就像你正在談論的那樣(將結果存儲在一個數組中)。我會如何將用戶名,姓名和圖片存儲在一起?我還沒有玩過多少字典,但我認爲他們只能存儲兩(2)個結果。我如何儲存所有三(3)? –

回答

1

試圖將不同的屬性存儲在不同的數組中會是一個問題,因爲正如您發現的那樣,最終會遇到某個用戶沒有屬性的問題。您可以使用一系列可選項,以便您可以將缺少的屬性存儲爲nil,但將PFObject本身存儲在單個數組中並訪問cellForRowAtIndexPath中的屬性比分離屬性要簡單得多。

由於提取照片需要單獨的異步操作,因此可以單獨存儲它。您可以使用由用戶ID編制索引的字典,而不是使用陣列來存儲檢索到的照片,這會有相同的排序問題;儘管對於大量的學生來說,使用諸如SDWebImage之類的東西來下載cellForRowAtIndexPath中所需的照片可能更有效率。

// 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 
} 

其他一些指針;

  • 使用_分隔字段名中的單詞在iOS世界中並不真正使用; camelCase是首選,所以fullName而不是full_name
  • 它看起來像您的解析查詢可能會更有效率,如果您有一個class字段或引用對象,以便您不需要提供其他類成員的數組。
+0

你是救命恩人,保羅!我必須做一些調試,並根據我遇到的一些問題在幾天內編輯您的答案,但總體而言,這是一種乾淨而簡單的方法!再次感謝! –

相關問題