我無法重新加載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