我无法重新加载tableView。当我的firebaseService.getAllPosts()
方法运行时,它会为我提供数据库中的两个帖子(如预期的那样)。我可以这样说,因为当didSet
打印运行时,它会给我正确的计数。但是,因为我知道tableview是在方法运行之前设置的,我知道我需要重新加载tableview来更新我的数据源中的计数。存在这个问题。我特意将posts
变量放在我的班级之外,以便可以从每个班级访问它。 (如果这不是一个好习惯,请告诉我。)无法重新加载tableView
我在哪里可以运行tableView.reloadData()
以便我的tableView数据源更新并给出正确的可能posts
?我试过把FeedController().tableView.reloadData()
放在didSet中,我试过把它放在viewDidLoad()
中,但这些都没有工作。我也尝试添加一个名为_posts
的变量,并将其设置为posts
,并将didSet
与中的didSet
相加,但这也不起作用。
class FeedController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let tableView = UITableView(frame: UIScreen.mainScreen().bounds, style: UITableViewStyle.Plain)
let cellId = "PhotoCell"
let textCellId = "TextCell"
let firebaseService = FirebaseService.sharedInstance
static let sharedFeedInstance = FeedController()
var posts = [Post]() {
didSet {
tableView.reloadData()
print(posts.count)
}
}
override func viewDidLoad() {
super.viewDidLoad()
firebaseService.getAllPosts()
tableView.dataSource = self
tableView.delegate = self
self.view.addSubview(tableView)
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
print("sections: \(posts.count)")
return posts.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let post:Post? = posts[indexPath.section]
if let _ = post?.imageContentName {
let photoFeedCell = tableView.dequeueReusableCellWithIdentifier(self.cellId, forIndexPath: indexPath) as? FeedTVCellWithPhoto
photoFeedCell?.post = post
return photoFeedCell!
}
let textFeedCell = tableView.dequeueReusableCellWithIdentifier(self.textCellId, forIndexPath: indexPath) as? FeedTVCellText
textFeedCell?.post = post
return textFeedCell!
}
}
更新1:从FirebaseService类getAllPosts方法
func getAllPosts() {
let postRef = ref.child("posts")
postRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
// print(snapshot.value)
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshots {
if let postDictionary = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let post = Post(key: key, dictionary: postDictionary)
FeedController.sharedFeedInstance.posts.insert(post, atIndex: 0)
}
}
}
})
}
你的问题是,你需要在屏幕上的视图控制器的上下文中执行'reloadData'; 'FeedController()。tableView.reloadData()'创建一个'FeedController'的新实例,这没有帮助。你可以得到你想要的一种方法是从'didSet'发布一个NSNotification,并让感兴趣的视图控制器订阅它。是的,全局变量是一个坏主意。创建一个单例类或创建一个实例并将其传递给您的每个视图控制器 – Paulw11
您需要能够知道getAllPosts何时结束,然后才能调用reloadData。 getAllPosts如何看起来像? – Cristik