2014-11-26 1 views
6

Swift에서 데이터를 업데이트 한 후 테이블보기를 다시로드하려고하는데 작동하지 않는 것 같습니다. 탭을 변경하고 돌아 가면 테이블보기가 다시로드되지만 자동으로 이동하지는 않습니다. 내가 이것을 보았 기 때문에iOS : swift에서 tableView.reloadData()가 작동하지 않습니다.

dispatch_async(dispatch_get_main_queue(), {() -> Void in 
    self.tableView.reloadData() 
}) 

: 그것은 목표 - C에서 작동하지만 스위프트 ... 에 나는 또한 넣어 시도 왜 이해가 안

override func viewDidLoad() { 
    super.viewDidLoad() 

    // some code 

    refresh(self) 
} 

func refresh(sender: AnyObject) { 
    // Reload the data 

    self.tableView.reloadData() 
} 

: 다음은 내 코드입니다 다른 게시물에서는 작동하지만 작동하지 않습니다.

편집을 돕는

감사 : 내 전체보기 컨트롤러 당신의 refresh 기능에

class HighwaysViewController: UITableViewController { 

    var highways: [Highway]! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // 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() 

     highways = [Highway]() 

     // On ajoute le "Pull to refresh" 
     refreshControl = UIRefreshControl() 
     refreshControl!.addTarget(self, action: Selector("refresh:"), forControlEvents: UIControlEvents.ValueChanged) 
     tableView.addSubview(refreshControl!) 

     refresh(self) 
    } 

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

    func refresh(sender: AnyObject) { 
     // Afficher l'icône de chargement dans la barre de status 
     UIApplication.sharedApplication().networkActivityIndicatorVisible = true 

     // On télécharge les autoroutes 
     var url = NSURL(string: "http://theurl.com")! // URL du JSON 
     var request = NSURLRequest(URL: url) // Création de la requête HTTP 
     var queue = NSOperationQueue() // Création de NSOperationQueue à laquelle le bloc du gestionnaire est distribué lorsque la demande complète ou échoué 

     // Envoi de la requête asynchrone en utilisant NSURLConnection 
     NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{(response: NSURLResponse!, data: NSData!, error: NSError!) ->Void in 
      // Gestion des erreurs de connexion 
      if error != nil { 
       // Masquer l'icône de chargement dans la barre de status 
       UIApplication.sharedApplication().networkActivityIndicatorVisible = false 

       println(error.localizedDescription) 
       let errorAlert = UIAlertView(title: "Erreur", message: error.localizedDescription, delegate: self, cancelButtonTitle: "OK") 
       errorAlert.show() 
      } 
      else { 
       // Récupération du JSON et gestion des erreurs 
       let json = JSON(data: data) 

       if let highwaysData = json.arrayValue { 
        for highway in highwaysData { 
         var newHighway = Highway(ids: highway["Ids"].stringValue, name: highway["Name"].stringValue, label: highway["Direction"].stringValue, length: highway["Length"].stringValue, directions: highway["Direction"].stringValue, operateur: highway["Operator"].stringValue) 
         self.highways.append(newHighway) 
        } 
       } 
      } 
     }) 

     if (self.refreshControl!.refreshing) { 
      self.refreshControl!.endRefreshing() 
     } 

     tableView.reloadData() // Here is the problem 

     // Masquer l'icône de chargement dans la barre de status 
     UIApplication.sharedApplication().networkActivityIndicatorVisible = false 
    } 

    // MARK: - Table view data source 

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     // Return the number of rows in the section. 
     return highways.count 
    } 

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

     // Configure the cell... 
     let tableCell = highways[indexPath.row] 

     let nameLabel = cell.viewWithTag(1) as UILabel 
     let directionLabel = cell.viewWithTag(2) as UILabel 

     nameLabel.text = tableCell.name! 
     directionLabel.text = tableCell.getDirections() 

     return cell 
    } 

    /* 
    // MARK: - Navigation 

    // In a storyboard-based application, you will often want to do a little preparation before navigation 
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
     // Get the new view controller using [segue destinationViewController]. 
     // Pass the selected object to the new view controller. 
    } 
    */ 

} 
+2

'viewDidLoad'에서만'refresh()'를 호출합니까? 보기 컨트롤러 당 한 번만 실행된다는 점에 유의하십시오. – Kirsteins

+0

viewDidLoad를 제외하고 어디에서 reloadData를 호출하나요? – Paulw11

+1

또한 refresh 메소드 내에서 자체에 대한 참조를 전달할 필요가 없습니다. –

답변

12

, 부하는 비동기 폐쇄를 사용하여 완료되지만 당신은 당신의 활동 표시를 업데이트하고, 외부에서 테이블을 다시로드 클로저이므로로드가 완료되기 전에 실행됩니다. 당신은 폐쇄 내부에이 코드를 이동하고 주요 큐에서 실행되는지 확인해야 당신이 (당신이처럼 소리) 탭 표시 줄 컨트롤러를 사용하는 경우,

func refresh(sender: AnyObject) { 
     // Afficher l'icône de chargement dans la barre de status 
     UIApplication.sharedApplication().networkActivityIndicatorVisible = true 

     // On télécharge les autoroutes 
     var url = NSURL(string: "http://theurl.com")! // URL du JSON 
     var request = NSURLRequest(URL: url) // Création de la requête HTTP 
     var queue = NSOperationQueue() // Création de NSOperationQueue à laquelle le bloc du gestionnaire est distribué lorsque la demande complète ou échoué 

     // Envoi de la requête asynchrone en utilisant NSURLConnection 
     NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{(response: NSURLResponse!, data: NSData!, error: NSError!) ->Void in 
      // Gestion des erreurs de connexion 
      if error != nil { 
       // Masquer l'icône de chargement dans la barre de status 
       UIApplication.sharedApplication().networkActivityIndicatorVisible = false 

       println(error.localizedDescription) 
       let errorAlert = UIAlertView(title: "Erreur", message: error.localizedDescription, delegate: self, cancelButtonTitle: "OK") 
       errorAlert.show() 
      } 
      else { 
       // Récupération du JSON et gestion des erreurs 
       let json = JSON(data: data) 

       if let highwaysData = json.arrayValue { 
        for highway in highwaysData { 
         var newHighway = Highway(ids: highway["Ids"].stringValue, name: highway["Name"].stringValue, label: highway["Direction"].stringValue, length: highway["Length"].stringValue, directions: highway["Direction"].stringValue, operateur: highway["Operator"].stringValue) 
         self.highways.append(newHighway) 
        } 
       } 
      } 

      dispatch_async(dispatch_get_main_queue(), { 

       if (self.refreshControl!.refreshing) { 
        self.refreshControl!.endRefreshing() 
       } 

       self.tableView.reloadData() 

       // Masquer l'icône de chargement dans la barre de status 
       UIApplication.sharedApplication().networkActivityIndicatorVisible = false 
      }) 

     }) 

    } 
+0

대단히 감사합니다. 완벽하게 작동하며 이제는 이해합니다. 내 실수! :) –

+1

추신 : 폐쇄에서 우리는'self' 변수를 호출해야합니다 :'self.tableView.reloadData()' –

+0

내 대답을 업데이트했습니다. 방금 코드를 복사 했으므로 놓쳤습니다. 개인적으로 나는 항상 혼란을 피하기 위해 '자기'를 사용하며, 항상 필요한 Obj C의 습관이기도합니다. – Paulw11

1

(가 UI를 업데이트로) 및 다른 탭에서 무언가를 수정 한 후에 테이블에서 새로 고침을 기다리고 있다면 대신 대상 뷰 컨트롤러의 viewWillAppear() 또는 viewDidAppear() 메서드 내부에서 tableView.reloadData()를 호출해야합니다. viewDidLoad()는 해당 뷰 컨트롤러의 수명 동안 한 번만 호출됩니다.

+0

아니요, 동일한 탭에서 새로 고침을 기다리고 있습니다. 데이터로드 후 테이블 뷰를 새로 고치지 만 작동하지 않습니다. –

+0

뷰 컨트롤러 코드가 더 필요합니다. "데이터로드 중"은 여러 가지 방법으로 수행 될 수 있습니다. – RiverbayChris

+0

내 게시물을 편집했습니다. –

관련 문제