调用方法获取数据计数数组时,无法从模型控制器中的数组中检索正确数量的对象

时间:2018-07-25 19:48:00

标签: ios arrays swift xcode

详细地说,我正在从firebase中检索数据,并从接收到的每个条目中创建一个餐厅对象数组,然后Im对数组中的元素数量进行计数,应该为5,23 :(餐厅#1)在数组中有5个元素,(餐厅#2)23(数据集中只有两个餐厅)。可以在我的模型控制器上完成

class OverviewModelController {

  //MARK: - SharedController
  static let sharedController = OverviewModelController()

  //MARK: - Source 
  var restaurantList = [Restaurant]() 
  var filteredList = [Restaurant]()

  //MARK: - FireBase Reference
  var ref: DatabaseReference?

  func fetchAllData() {        
    self.ref = Database.database().reference()
    self.ref?.child("restaurants").observe( .childAdded , with: { (snap) in
        guard let topArray = snap.value as? [[String:Any]] else {print(":(") ; return }
        var restaurantArray = [Restaurant]()

        for dictionary in topArray {                
            guard let address = dictionary["address"] as? String,
                let city = dictionary["city"] as? String,
                let inspectionDate = dictionary["inspectionDate"] as? String,
                let name = dictionary["name"] as? String,
                let major = dictionary["major"] as? Int,
                let minor = dictionary["minor"] as? Int,
                let violationTitle = dictionary["violationTitle"] as? String else { continue }

            //MARK: - creates restaurants from the list above
            let restaurant = Restaurant(address: address, city: city, inspectionDate: inspectionDate, name: name, major: major, minor: minor, violationTitle: violationTitle)

            //MARK: - Adds a restaurant to restaurant array instance
            restaurantArray.append(restaurant)                
        }                      
        self.restaurantList = restaurantArray
       print(self.restaurantList.count)
    })             
}

一旦我在viewcontroller上运行上面的方法,它会从加载的视图中打印正确的计数,但是如果我从viewController中的方法检查restaurantList计数,我只会得到23的反对,即5、23。我想我是我做错了一点点损失。我知道我做的事情只能让我接受最后的餐厅。我以为我是通过共享控制器传递数据数组的,但是并没有给我想要的结果。视图控制器如下:

class MapViewController: UIViewController, UISearchBarDelegate {
    @IBOutlet weak var mapView: MKMapView!

  @IBOutlet weak var homeSearchBar: DesignableSearchBar!

  var finalArray = [Restaurant]()

  override func viewDidLoad() {
    super.viewDidLoad()

    FirebaseApp.configure()
   homeSearchBar.delegate = self
    fetch()             
  }

  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)        
  }

  func fetch() {         
    OverviewModelController.sharedController.fetchAllData()                    
  }            

  func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {        
    print(OverviewModelController.sharedController.restaurantList.count)

    self.homeSearchBar.resignFirstResponder()

    DispatchQueue.main.async {          
        self.homeSearchBar.text = ""        
    }                
  }

0 个答案:

没有答案