通过swift附加数组2

时间:2016-01-23 13:26:54

标签: ios arrays swift append

我有附加数组的问题,你可以看到我的代码,我检查了问题' s line by:self.items.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()中,但是它可以工作......但我需要它在它之外(比如我的代码)..
我试图将数组放在异步块之外......仍然没有附加
....任何一个?

1 个答案:

答案 0 :(得分:0)

我认为您的代码有效! 问题是 : 为什么你认为你的数组仍然是空的? 您必须考虑执行指令的顺序。 在这一行:

// print(self.items);

您的数组仍然为空,因为尚未调用闭包。 将这一行放在追加之后,你会看到。

而且,只需在追加后添加self.tableView.reloadData() ,您就会很高兴:) (它会告诉你的tableview调用委托方法(numberOfRowsInSection ...))