tableview的数据源数组值自动更改为0

时间:2015-12-22 12:55:52

标签: ios swift uitableview xcode7

 var noteList:NSMutableArray = NSMutableArray() // declaration of `noteObjects`


    query.findObjectsInBackgroundWithBlock { ( objects, error) -> Void in

        if (error == nil) {


            let temp: NSArray = objects as NSArray!



            self.noteList = temp.mutableCopy() as! NSMutableArray


            self.tableView.reloadData()

        }else {
            print(error!.userInfo)

        }
    }
    //populating noteObjects

我有一个tableView,他们的数据源是一个数组' noteObjects'它的类型是NSMutableArray,所以问题是每次我打开我的tableView我的' noteObjects'数组的值为0,但随后会自动更改为所需的值,我该怎么说呢?我在tableViewController的不同阶段做到了这一点 -

我在noteObjects.count

中打印了ViewDidload
override func viewDidLoad() {
       super.viewDidLoad()


    print("\(noteObjects.count) viewDidlaod3") }  

输出:

0 viewDidlaod3

cellForRowAtindexPath里面我打印了这个

  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

  print("\(noteObjects.count) in cellForAtIndexPath")       
return cell }

输出: 18 in cellForAtIndexPath

如果我移动到另一个View然后再次打开这个tableView它会继续给出sae结果,(首先注意object.count = 0)

我想使用那个noteObjects.count,以便我可以确认,如果tableView的数据源为空,这样我就可以显示一条消息,但是当我使用它时,它总是显示我的tableview是空的,因为at首先noteObjects.count是0

如果上面提供的详细信息不够,请告诉我,我会解决它

3 个答案:

答案 0 :(得分:1)

api调用'findeObjectsInBackground'是异步的,意味着在不同的线程中获得结果时,后续执行闭包。因此,在数据准备就绪时返回主线程并重新加载表视图将解决问题。您可以阅读有关这些类型的闭包的更多信息,因为它们在iOS中非常常见。

query.findObjectsInBackgroundWithBlock { ( objects, error) -> Void in

        if (error == nil) {
            let temp: NSArray = objects as NSArray!
            dispatch_async(dispatch_get_main_queue(), {
                 self.noteList = temp.mutableCopy() as! NSMutableArray
                 self.tableView.reloadData()
            })
        } 
        else {
            print(error!.userInfo)
        }
}

答案 1 :(得分:0)

刚刚将我的代码从viewDidLoad移到了viewDidAppear,这对我来说很有用

override func viewDidAppear(animated: Bool) {
      super.viewDidAppear(animated)



        self.fetchAllObjectsFromLocalDataStore()

    print("\(noteObjects.count) view appears")



    if noteObjects.count < 1 {

        let Alert = UIAlertView(title: "No Data to Display", message: "ther's nothing bro you should pull to refresh", delegate: self, cancelButtonTitle: "OKAY Got IT")
        Alert.show()

    }
    } 

现在noteObject.count在更新其值

后正在检查

答案 2 :(得分:0)

在同步方法

之后使用if语句
  if noteObjects.count < 1 {

    let Alert = UIAlertView(title: "No Data to Display", message: "ther's nothing bro you should pull to refresh", delegate: self, cancelButtonTitle: "OKAY Got IT")
    Alert.show()

}
相关问题