現在swiftでAppDelegateで宣言したNSMutableArrayの要素を別画面で保存・取得したいと思っています。
(AppDelegateで宣言・初期化→A画面で保存→B画面で取り出し)
しかし、B画面で取得する時に
fatal error: unexpectedly found nil while unwrapping an Optional value
のエラーで止まってしまいます。
ソースコードはこちらになります。
###AppDelegate
swift
1var answerArray:NSMutableArray? 2 3func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: 4 [NSObject: AnyObject]?) -> Bool { 5 6 let answerArray = [0,0,0,0,0,0] 7 print(answerArray)//[0,0,0,0,0,0] 8}
###aViewController
swift
1var answerArray:NSMutableArray? 2 3override func viewDidLoad() { 4 5 //bボタン 6 q1_1btn = UIButton() 7 q1_1btn.frame = CGRectMake(200,50,60,60) 8 q1_1btn.setTitle("ボタンA", forState: UIControlState.Normal) 9 q1_1btn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) 10 q1_1btn.tag = 1 11 q1_1btn.addTarget(self, action: #selector(QuestionViewController.selectbtn(_:)), forControlEvents: .TouchUpInside) 12 self.view.addSubview(q1_1btn) 13 14 internal func selectbtn(sender: UIButton){ 15 print("sender.tag:\(sender.tag)") //1 16 let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 17 //押したボタンのタグをarrayに格納 18 let tag = sender.tag 19 appDelegate.answerArray![0] = tag 20 let secondViewController = bViewController() 21 self.navigationController?.pushViewController(secondViewController, animated: true) 22} 23
###bViewController
swift
1var str:NSArray? 2 3override func viewDidLoad() { 4 5 self.view.backgroundColor = UIColor.whiteColor(); 6 let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 7 8 let num:Int = appDelegate.answerArray![0] as!Int //ここでfatal error 9 print(appDelegate.answerArray) //nilと返されます 10 11} 12 13
###追加
追加の質問になります。
こちらのコードでtxtファイルの文章をstrに入れ、Labelに反映させる処理を書いているのですが、Labelに文章が表示されません...
どう書き換えれば良いでしょうか?
よろしくお願い致します。
var str: [[String]] = [] if let csvPath = NSBundle.mainBundle().pathForResource("Type", ofType: "txt") { // var str: [[String]] = [] do { let csvString = try NSString(contentsOfFile: csvPath, encoding: NSUTF8StringEncoding) as String csvString.enumerateLines{ line, stop in // 行の途中に","が含まれていたら、配列の要素として切り抜く let str2: [String] = line.componentsSeparatedByString(",") str.append(str2) } // 何かしらのエラーがあると以下に入る } catch _ { print("何らかのエラーが発生しました") } print(str) } let type:Int = appDelegate.answerArray![0] as! Int print(type) let resultLabel: UILabel = UILabel(frame: CGRectMake(60,250,200,200)) resultLabel.text = str[type]as?String resultLabel.backgroundColor = UIColor.blueColor() resultLabel.textColor = UIColor.blackColor() self.view.addSubview(resultLabel)

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/06/29 02:40
2016/06/29 03:06
2016/06/29 07:28