从另一个视图控制器访问数组数据
在TerningspilletSpillereViewController
我有一个数组,看起来像这样:
var mineSpillere = ["1SP", "2SP", "3SP"]
这下:
func assignArray() { let obj = TerningspilletViewController() obj.mineSpillere2 = self.mineSpillere }
在我的其他UIViewController
( TerningspilletViewController
)我有这个
var mineSpillere2 = [String]()
我想从一个函数中像这样产生一个随机(1SP,2SP或3SP)button点击:
func generateNumber() { let array = aBB let randomIndex = Int(arc4random_uniform(UInt32(array.count))) randomLabel.text = (array[randomIndex]) }
但是这给了我以下错误:
致命错误:数组索引超出范围。
我这行randomLabel.text = (array[randomIndex])
这是为什么?
看到这个例子,并更新您的使用。 我不是很了解你的命名,但是这是如何从不同的视图控制器(用数据初始化)获取数据。
第一视图控制器:
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) } }
第二视图控制器:
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. } */ }
出现这种错误的原因有两个:
- 数组长度在对
array.count
的调用和数组访问之间改变。 这只有在您从另一个线程分配或修改数组时才会发生 - 该数组是空的,在这种情况下,
arc4random_uniform
永远不会产生0<=X<0
(无论返回的结果是什么,都将触发索引超出范围exception)。
所以,如果你不使用多个线程,检查数组是否为空。