简体   繁体   中英

Access array data from another view controller

In TerningspilletSpillereViewController I have an array that looks like this:

var mineSpillere = ["1SP", "2SP", "3SP"]

and this under:

func assignArray() {
   let obj = TerningspilletViewController()
   obj.mineSpillere2 = self.mineSpillere
}

In my other UIViewController ( TerningspilletViewController ) I have this

var mineSpillere2 = [String]()

I want to generate a random (1SP, 2SP or 3SP) on button click like this from a function:

func generateNumber() {
    let array = aBB
    let randomIndex = Int(arc4random_uniform(UInt32(array.count)))

    randomLabel.text = (array[randomIndex])
}

But this gives me the following error:

fatal error: Array index out of range.

I this line randomLabel.text = (array[randomIndex])

Why is that?

See this example and update for your usage. I'm not quite understanding your naming but this is how you can get the data from a different view controller (that is initialized with the data).

First View Controller:

import UIKit

class ViewController: UIViewController {

var arrayWithoutData = [String]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    assignArray()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func assignArray() {

    let otherVC = NextViewController()
    arrayWithoutData = otherVC.mineSpillere

    println(arrayWithoutData)

}

}

Second View Controller:

import UIKit

class NextViewController: UIViewController {

var mineSpillere = ["1SP","2SP","3SP"]

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

That error could occur for two reasons:

  • The array length changes between the call to array.count and the array access. This could only happen if you assign or modify the array from another thread
  • The array is empty, in which case arc4random_uniform can never produce a number 0<=X<0 (and whatever it returns will trigger an index-out-of-bounds exception).

So if you are not using multiple threads, check if the array is empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM