2016-08-31 3 views
1

헤드 업과 마찬가지로 Firebase를 사용하여 데이터를 저장/제거합니다.TableView에서 삭제할 때 인덱스가 범위를 벗어 났습니까?

override func viewDidLoad() 
{ 
    super.viewDidLoad() 

    observePeople() 

    tableView.delegate = self 
    tableView.dataSource = self 

} 

observePeople() 메소드 (I 두 번 여기에 테이블을 다시로드)과 같이 운영

func observePeople() 
{ 
    let ref = FIRDatabase.database().reference().child("Users") 
    ref.observeEventType(.ChildAdded, withBlock: 
    { (snapshot) in 

     if let firstname = snapshot.value?.objectForKey("firstname"), lastname = snapshot.value?.objectForKey("lastname") 
     { 
      let fullname = "\(firstname) \(lastname)" 
      self.names.append(fullname) 

      dispatch_async(dispatch_get_main_queue()) 
      { 
       self.tableView.reloadData() 
      } 
     } 

    }, withCancelBlock: nil) 

    ref.observeEventType(.ChildRemoved, withBlock: 
    { (snapshot) in 

    if let firstname = snapshot.value?.objectForKey("firstname"), lastname = snapshot.value?.objectForKey("lastname"), dateOfBirth = snapshot.value?.objectForKey("Date of Birth"), zipcode = snapshot.value?.objectForKey("Zipcode") 
    { 
     print("We deleted the person \(firstname) \(lastname) with the details: \(dateOfBirth), \(zipcode)") 
     self.tableView.reloadData() 
    } 

    }, withCancelBlock: nil) 
} 

와의

내 viewDidAppear 나는 테이블을 다시 새로 고침 : 여기

내 viewDidLoad에 코드입니다 :

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

마지막으로 색인을 말한 오류가 발생하는 행을 삭제합니다. 이자형. 흥미로운 점은 테이블을 4 개 항목으로 채우는 경우입니다. 첫 번째 항목을 삭제하면 두 번째 항목이 실제로 삭제되고, 세 번째 항목을 삭제하면 네 번째 항목이 삭제됩니다. 나는이 현상을 관찰 할 수있는 중단 점을 추가했다. 그리고 tableview에서 제거한 직후에 중단된다.

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) 
{ 
    if editingStyle == .Delete 
    { 
     let ref = FIRDatabase.database().reference().child("Users") 
     ref.observeEventType(.ChildAdded, withBlock: { (snapshot) in 

      if let firstname = snapshot.value?.objectForKey("firstname"), lastname = snapshot.value?.objectForKey("lastname") 
      { 
       let fullname = "\(firstname) \(lastname)" 
       let currentName = self.names[indexPath.row] 

       if fullname == currentName 
       { 
        print("We have a match") 
        let currentKey = snapshot.key 
        ref.child(currentKey).removeValue() 

        dispatch_async(dispatch_get_main_queue()) 
        { 
         self.tableView.reloadData() 
        } 
       } 

      } 

      }, withCancelBlock: nil) 
    } 

     names.removeAtIndex(indexPath.row) 
     tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) 
    } 
} 

그래서 바로 tableView.deleteRows 메소드 다음에 오류가 발생합니다. 이것에 잠시 동안 있었고 그것을 찾을 수없는 것 같습니다. 또한 필자는 항상 데이터베이스와 배열에 대해 배열이 일치하는지 확인하여 채워지기 전에 동시에 비어 있습니다.

+0

제거 당신의 .ChildRemoved 리스너에서 삭제 기능에이 코드를'self.tableView.reloadData()'이름의 제거를 삽입합니다. 이후 삭제 tableview 자체를 업데이 트하십시오. 'print (currentName)'체크는 아이디어를 줄 것이다. –

+0

아, 그게 작동하지 않았 겠지만 내 currentName을 추적하기 위해 인쇄 할 것입니다 –

답변

2

을 파견하기 전에 이러한 라인을 이동해야합니다 생각합니다. 배열에서 삭제 한 다음 tableView에서 행을 삭제해야한다고 생각할 수도 있습니다. 왜냐하면 대부분의 경우 배열 데이터로 수행하는 작업이 있기 때문입니다.하지만 그렇게하면 firebase이 쿼리하거나 청취 할 때 문제가 발생합니다. 이를 처리하는 가장 좋은 방법은 배열이나 테이블에서 commitEditingStyle 함수로 어떤 데이터도 수동으로 삭제하지 않는 것입니다. 대신 firebase에서 값을 제거하십시오. 그런 다음 .ChildRemoved 수신기에서 데이터 배열에서 개체를 제거하고 테이블을 다시로드하십시오.

names.removeAtIndex(indexPath.row) 
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) 

을 삭제하고

ref.observeEventType(.ChildRemoved, withBlock: 
{ (snapshot) in 

if let firstname = snapshot.value?.objectForKey("firstname"), lastname = snapshot.value?.objectForKey("lastname"), dateOfBirth = snapshot.value?.objectForKey("Date of Birth"), zipcode = snapshot.value?.objectForKey("Zipcode") 
{ 
    print("We deleted the person \(firstname) \(lastname) with the details: \(dateOfBirth), \(zipcode)") 
    let fullname = "\(firstname) \(lastname)" 
    if let index = names.indexOf(fullname) { 
     names.removeAtIndex(index) 
     self.tableView.reloadData() 
    } 
} 

}, withCancelBlock: nil) 
+0

Ahhhh 말이 맞습니다. 매우 통찰력, 정말 고마워요! 이것은 내가 필요한 것입니다. –

0

난 당신이 일반적으로 테이블에 대해 작업하는 방법을 중포 기지 변경 작업

names.removeAtIndex(indexPath.row) 
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) 
+0

전에 시도했지만 작동하지 않았습니다 –

관련 문제