Global variable not updated

I’ve got a global variable that I’m trying to update in one class and then pass to another class to update a UITableview.

The first class looks like this:

class MapViewController: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate {

    var distance: Float = 0.0

    //Called once a second
    func updateLocation() {
        if let mylocation = mapView.myLocation {
            self.distance += Distance(self.lastLocation, Coordinate2: mylocation.coordinate)
            println(self.distance)
            self.lastLocation = mylocation.coordinate
        }
    }
    func fetchValues(instrument: String) -> AnyObject {
        if instrument == "Distance" {
            return self.distance
        }
        else {
            return ""
        }
    }
}

In my second class I have the following:

class StatusViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

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

        let cell: StatusCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as StatusCell
        let value = MapViewController()
        if indexPath.row == 1 {
            var distance: Float = Float(value.fetchValues("Distance") as NSNumber)/1.852
            cell.InstrumentValue.text = distance.description + " Nm"
        }
    }

    override func viewWillAppear(animated: Bool) {
        TableView.reloadData()
    }
}

The function is called every time I open the tab as I intended but for some reason the first class passes 0.0 every time, even after my updateLocation() function correctly updates distance and prints it to Xcode. What’s happening here?

There are no global variables in this story. distance
in the first file is a property – an instance variable. You can only get the particular value of a particular instance of this class (MapViewController). There can be many MapViewController instances, each with a different distance
.

You are saying value.fetchValues
, but what is value
exactly? I have no reason to believe that value
is the correct instance here. And the fact that you are having this problem suggests that it is not. How are you obtaining value
?

For example, if you are instantiating a new MapViewController, then of course its
distance
is the default, 0
– it is not the same MapViewController whose distance
is being updated.

EDITNow you have edited your question to reveal that you are saying:

let value = MapViewController()

It is just as I had guessed. There’s your problem.

Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 移动开发 » Global variable not updated

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录