AruLNadhaN
AruLNadhaN

Reputation: 2826

Can't retain array data outside of method in SWIFT

I am storing the category name from a JSON in an Array using alamofire .

The array has values only when it is called from this Method CategoryNameFunc.

If i call the the array from the tableview or any other method it always returns 0

CODE

    var CategoryNameArray : [String] = []

        override func viewDidLoad() {
            super.viewDidLoad()
            Network()
            tester()
        }

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return CategoryNameArray.count     // This returns 0
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell : UITableViewCell = self.TableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell

    println(self.CategoryNameArray[indexPath.row])

    cell.textLabel?.text = "Hello"

    return cell
}


        func Network(){
            Alamofire.request(.GET, "http://www.wive.com/index.php/capp/category_list")
                .responseJSON { (_, _, data, _) in
                    let json = JSON(data!)
                    let count = json.count
                    self.CategoryNameFunc(json, Count: count) }
        }

        func CategoryNameFunc(Json: JSON, Count: Int)
        {
            for index in 0...Count-1 {
                let name = Json[index]["CATEGORY_NAME"].string
                CategoryNameArray.append(name!)
            }
            // This returns 23 (The correct value)
               println(self.CategoryNameArray.count)
        }

Upvotes: 1

Views: 188

Answers (2)

Dejan Skledar
Dejan Skledar

Reputation: 11435

I am not sure (didn't use Almofire) but it think, this happens because the method Network, more precisly the Almofire request is fired asynchronously.

So, the methods Network() and tester() are running simultaneously, but because Network() needs to fetch data first, tester() is faster and is executed first.

The proper way to execute tester() and Network() one after another would be:

   func CategoryNameFunc(Json: JSON, Count: Int)
    {
        for index in 0...Count-1 {
            let name = Json[index]["CATEGORY_NAME"].string
            CategoryNameArray.append(name!)
        }
        // run tester, AFTER you have the data.
        tester()
    }

Upvotes: 0

Okhan Okbay
Okhan Okbay

Reputation: 1394

When you called Network() function it creates a new thread (Alamofire start an asynchronous request) and your tester() function is not waiting for your Network() function to finish before you count your CategoryNameArray().But your CategoryNameFunc() function waits for network operation to finish.

Upvotes: 1

Related Questions