2016-08-07 2 views
1

아마도이 간단한 문제 일 수 있으므로 도움을 받으시겠습니까? 쿼리 내 Parse 쿼리는 내가 찾고있는 개체를 인쇄하지만 배열에 추가 할 수 없습니다. 에서 UITableView에서 검색 할 수 있습니다.쿼리 내에서 쿼리를 Swift/Parse로 추가하지 않음

셀에서 쿼리 결과를 큐에서 제거 할 때 오류는 "치명적인 오류 : 인덱스가 범위를 벗어났습니다."입니다.

수입 UIKit 수입 구문 분석 수입 볼트

클래스 MessagesTableVC : 여기

코드의있는 UITableViewController를 같아요다시피 {

var usernames = [String]() 
var sentDate = [NSDate]() 
var details = [String]() 
var userImage = [PFFile]() 


@IBAction func backToProfile(sender: AnyObject) { 
    self.performSegueWithIdentifier("messagesToProfile", sender: self) 
} 


override func viewDidLoad() { 
    super.viewDidLoad() 

    let messagesQuery = PFQuery(className: "Messages") 
    messagesQuery.whereKey("recipientId", equalTo: PFUser.currentUser()!.objectId!) 
    messagesQuery.includeKey("senderId") 
    messagesQuery.orderByDescending("createdAt") 
    messagesQuery.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in 

     if error != nil { 
      print(error) 
     } 

     if error == nil { 

      if let objects = objects { 

       self.usernames.removeAll(keepCapacity: true) 
       self.sentDate.removeAll(keepCapacity: true) 
       self.details.removeAll(keepCapacity: true) 
       self.userImage.removeAll(keepCapacity: true) 

       for object in objects { 

        self.sentDate.append(object.createdAt! as NSDate) 

        if (object["item"] != nil) { 
        self.details.append(object["item"] as! String) 
        } else { 
        self.details.append(object["request"] as! String) 
        } 

        let senderObject = (object["senderId"] as! PFUser) 
        let senderId = (senderObject.objectId! as String) 

        print(senderId) 

        // Query for sender info 
        let userQuery = PFUser.query() 
        userQuery?.whereKey("objectId", equalTo: senderId) 
        userQuery?.getFirstObjectInBackgroundWithBlock({ (object, error) in 

         self.usernames.append((object!["username"] as! String)) 

         //self.userImage.append(object!["profilePicture"] as! PFFile) 

        }) 




       } 

       dispatch_async(dispatch_get_main_queue()) { 
        self.tableView.reloadData() 
        //self.search.resignFirstResponder() 
       } 
      } 


    } 
    }) 

    // Uncomment the following line to preserve selection between presentations 
    // self.clearsSelectionOnViewWillAppear = false 

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller. 
    // self.navigationItem.rightBarButtonItem = self.editButtonItem() 
} 


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


// MARK: - Table view data source 

override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    // #warning Incomplete implementation, return the number of sections 
    return 1 
} 


override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    // #warning Incomplete implementation, return the number of rows 
    return sentDate.count 
} 


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("messageCell", forIndexPath: indexPath) as! MessageTableViewCell 

    //print(usernames[indexPath.row]) 
    cell.senderUsername.text = usernames[indexPath.row] 
    cell.itemOrPreview.text = details[indexPath.row] 

    let date = sentDate[indexPath.row] 
    let formatter = NSDateFormatter() 
    formatter.dateStyle = NSDateFormatterStyle.LongStyle 
    formatter.timeStyle = .ShortStyle 
    let dateString = formatter.stringFromDate(date) 
    cell.sentDate.text = dateString 


    //userImage[indexPath.row].getDataInBackgroundWithBlock { (data, error) in 
     // if let downloadedItemImage = UIImage(data: data!) { 
     // cell.senderImage?.image = downloadedItemImage 
     //} 
    //} 


    return cell 
} 

override func viewWillAppear(animated: Bool) { 
    tableView.reloadData() 
} 

}

+2

로컬 변수와 같은 온라인 데이터베이스로 작업 할 수 없습니다 ... getFirstObjectInBackgroundWithBlock'을 수행하는 모든 반환 된 객체에 대해'findObjectsInBackgroundWithBlock' 함수를 호출하면 그 중 가장 가난한 디자인입니다 !! 네트워크 요청 aint 싸구려 !! ... 오류가 당신은 내가'.removeAll (keepCapacity : true)'진짜로 않습니다 google을 얻고있다 ... –

+0

안녕하세요 마젤 토브 - 귀하의 응답을 주셔서 감사합니다. 어떻게 할 건데? – jwhubert91

답변

1

, 당신은 일관성 얻을 수 있습니다 요소 수는 sentDateusernames이므로 비동기식 getFirstObjectInBackgroundWithBlock 메서드를 통해 usernames에 추가하십시오. 따라서 tableView에서 reloadData를 호출 할 때 모든 사용자 이름이 usernames에 추가되지 않았을 수 있습니다. usernames에있는 항목 수가 더 적고 에 tableview 콜백이 발생할 때까지 그리고 numberOfItems에 sentDate에있는 항목 수가 반환 될 때까지 항목이 적을 수 있습니다.

처음에는 리팩터링 할 때 코드가 필요하다는 것을 수정하기 위해 여러 가지 문제가 발생할 수 있습니다. 구체적인 조언은하지 않겠지 만, tableView를 다시로드하기 전에 모든 데이터를 얻기 전에 기다려야 할 수도 있습니다.

관련 문제