【问题标题】:Swift Array not being appended toSwift Array 未附加到
【发布时间】:2016-08-30 14:41:36
【问题描述】:

我正在尝试获取一个 tableview 来显示解析的数据,但是没有附加应该填充我的 tableview 的数组。 有人可以快速查看一下,让我知道我做错了什么吗?

import UIKit
import SwiftKeychainWrapper
import Firebase

class FeedVC: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet var tableView: UITableView!

var posts = [Post]()

override func viewDidLoad()
{
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self


    DataService.ds.REF_POSTS.observeEventType(.Value, withBlock: { snapshot in
        if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot]
        {
            for snap in snapshot
            {

                if let postDict = snap.value as? Dictionary<String, AnyObject>
                {
                    let key = snap.key
                    let post = Post(postID: key, postData: postDict)
                    self.posts.append(post)

                }
            }
        }
    })

    tableView.reloadData()


}

override func viewDidAppear(animated: Bool) {

}

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

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return posts.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

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

    let post = posts[indexPath.row]
    print("\(post.caption)")


    return tableView.dequeueReusableCellWithIdentifier("PostCell") as! PostCell
}






@IBAction func signOutBtnTapped(sender: UIButton) {

    KeychainWrapper.defaultKeychainWrapper().removeObjectForKey(KEY_UID)
    try! FIRAuth.auth()?.signOut()
    performSegueWithIdentifier("toSignInVC", sender: nil)
}


}

谢谢大家。

【问题讨论】:

  • 您确定您的阵列没有被填充吗?尝试在您的封闭内打印它。如果它打印一个填充值,请将您的 reloadData 也放入闭包中,以确保在闭包结束后重新加载您的 tableView。
  • 在 for 循环结束后做 tableView.reloadData()
  • ... 但在 observeEventType 的完成处理程序中。
  • 你能更好地描述发生了什么吗? self.posts.append(post) 这条线从未被调用过吗?即使在调用回调块之后,数组posts 是否为空?或者即使数组包含元素,表格视图也不显示任何行?

标签: ios arrays swift uitableview


【解决方案1】:

您的数据检索似乎是一个异步操作,它可能在表格呈现之前没有完成。尝试在 self.posts.append(post) 之后的新行或完成块的末尾重新加载表数据。

【讨论】:

  • 整个循环结束后重新加载不是更好吗?
  • 非常感谢。睡前我一直醒着,试图弄清楚这一点!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-11
  • 2015-06-10
  • 1970-01-01
  • 1970-01-01
  • 2018-05-16
相关资源
最近更新 更多