我 append 数组时遇到问题,您可以查看我的代码,我通过以下方式检查了问题的行:self.items.append(....)
该数组未 append 并保持为空。
这是我的代码:
//
// ViewController.swift
// firer
//
// Created by mike matta on 06/01/2016.
// Copyright © 2016 Mikha Matta. All rights reserved.
//
import UIKit
import Firebase
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var showdatA: UILabel!
@IBOutlet weak var tableView: UITableView!
var items:[String] = []
var userFNAME:String = ""
var userDOB:String = ""
let textCellIdentifier = "TextCell"
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
// Do any additional setup after loading the view, typically from a nib.
///////////
let UsersChannel = Firebase(url: "https://MYFIREBASE.firebaseio.com/users")
UsersChannel.observeEventType(.ChildAdded, withBlock: { snapshot in
if let az = String?((snapshot.value.objectForKey("full_name"))! as! String) {
self.userFNAME = az
}
if let az2 = String?((snapshot.value.objectForKey("dob"))! as! String) {
self.userDOB = az2
}
print("\(self.userFNAME) - \(self.userDOB)")
self.items.append(self.userFNAME) // heeereeee what i am trying to doooooooo
})
// print(self.items)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as UITableViewCell
let row = indexPath.row
cell.textLabel?.text = items[row]
return cell
}
// MARK: UITableViewDelegate Methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let row = indexPath.row
print(items[row])
}
}
我尝试将数组定义放在 viewdidload() 内,它可以工作......但我需要它在它外面(就像我的代码)......
我也尝试将数组放在异步 block 之外...仍然没有 append ....任何一个吗?
最佳答案
我认为你的代码有效! 问题是 : 为什么你认为你的数组仍然是空的? 您必须考虑指令的执行顺序。 在这一行:
//print(self.items);
您的数组仍然是空的,因为尚未调用闭包。 将此行放在 append 后面,您就会看到。
而且,只需在追加后添加 self.tableView.reloadData()
即可,您会很高兴:)
(它会告诉你的tableview调用委托(delegate)方法(numberOfRowsInSection ...))
关于ios - 通过 swift 2 追加数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34964040/