从另一个视图控制器访问数组数据 [英] Access array data from another view controller

查看:24
本文介绍了从另一个视图控制器访问数组数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TerningspilletSpillereViewController 中,我有一个如下所示的数组:

In TerningspilletSpillereViewController I have an array that looks like this:

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

下面:

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

在我的另一个 UIViewController (TerningspilletViewController) 中,我有这个

In my other UIViewController (TerningspilletViewController) I have this

var mineSpillere2 = [String]()

我想从函数中像这样在按钮点击时生成随机(1SP、2SP 或 3SP):

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])
}

但这给了我以下错误:

致命错误:数组索引超出范围.

fatal error: Array index out of range.

我这一行 randomLabel.text = (array[randomIndex])

这是为什么?

推荐答案

查看此示例并更新以了解您的用法.我不太了解你的命名,但这是你如何从不同的视图控制器(用数据初始化)获取数据的方法.

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).

第一个视图控制器:

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.
}
*/

}

这篇关于从另一个视图控制器访问数组数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆