質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

1回答

1550閲覧

xcodeのエラーについて

JunZenpou

総合スコア24

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

0クリップ

投稿2017/06/26 08:11

###発生している問題・エラーメッセージ
以下のコードで、LogviewControllerでcell.time.text = "時間:" + dataDetail[1]の部分がエラーthread1 :EXC_BAD_INSTRUCTIONが発生しています。
型などを色々調べたのですが、エラーが中々消えません。
アドバイス宜しくお願いいたします。

MainViewControler

// // ViewController.swift // office_alerm // // Created by wdm_zen on 2017/05/26. // Copyright © 2017年 wdm_zen. All rights reserved. // import UIKit //aotuplayerのライブラリ import AVFoundation //Log出力のライブラリ import os.log class MainviewController: UIViewController, AVAudioPlayerDelegate { static let log = OSLog(subsystem: "com.wdmlimited", category: "UI") var timer:Timer = Timer() var audioPlayer:AVAudioPlayer! @IBOutlet weak var Button_1: UIButton! @IBOutlet weak var Button_2: UIButton! @IBOutlet weak var Button_3: UIButton! @IBOutlet weak var Button: UIButton! // @IBOutlet weak var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // スリープしない為の処理 UIApplication.shared.isIdleTimerDisabled = true // 音楽再生開始 let audioUrl1 = URL(fileURLWithPath: Bundle.main.path(forResource: "sample3", ofType:"mp3")!) // auido を再生するプレイヤーを作成する var audioError:NSError? do { audioPlayer = try AVAudioPlayer(contentsOf: audioUrl1) } catch let error as NSError { audioError = error audioPlayer = nil } // エラーが起きたとき if let error = audioError { print("Error \(error.localizedDescription)") } audioPlayer.delegate = self audioPlayer.prepareToPlay() // 音楽再生終了 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // 予約済みボタンタップ処理 @IBAction func Button_1_Tapped(_ sender: AnyObject) { // ファイル生成開始 // 時刻設定 let formatter = DateFormatter() formatter.dateFormat = "yyyy/MM/dd HH:mm:ss" //表示形式を設定 //現在時刻 let now = Date(timeIntervalSinceNow: 0) //"Dec 13, 2016, 4:10 PM" //現在時刻を文字列で取得 let nowString = formatter.string(from: now) //"2016/12/13 16:10:31" //fileを作成して、logをファイルに書き込む! // 作成するテキストファイルの名前 let textFileName = "reserved.txt" let initialText = "予約済み," + nowString + "\n" // URL // DocumentディレクトリのfileURLを取得 let documentDirectoryFileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last // ディレクトリのパスにファイル名をつなげてファイルのフルパスを作る(url) let targetTextFilePath = documentDirectoryFileURL?.appendingPathComponent(textFileName) // Path // Documentディレクトリのパスを文字列で取得 let checkValidation = FileManager.default let FileURL = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last // ディレクトリのパスにファイル名をつなげてファイルのフルパスを作る(path) let Path = FileURL! + "/" + textFileName // DocumentディレクトリのfileURLを取得 // fileが存在するかどうかの処理 if (checkValidation.fileExists(atPath: Path)){ os_log("reserved.txtファイルあり", log: MainviewController.log, type: .default) do { let fileHandle = try FileHandle(forWritingTo: targetTextFilePath!) // 改行を入れる let stringToWrite = "予約済み," + nowString + "\n" // ファイルの最後に追記 fileHandle.seekToEndOfFile() fileHandle.write(stringToWrite.data(using: String.Encoding.utf8)!) } catch let error as NSError { print("failed to append: \(error)") } }else{ os_log("reserved.txtファイルなし", log: MainviewController.log, type: .default) do { try initialText.write(to: targetTextFilePath!, atomically: true, encoding: String.Encoding.utf8) } catch let error as NSError { print("failed to write: \(error)") } } // ファイル生成終了 os_log("アラームボタン押したよ", log: MainviewController.log, type: .default) if ( audioPlayer.isPlaying ){ audioPlayer.stop() Button.setTitle("もう一度ベルを押してください!", for: UIControlState()) } else{ audioPlayer.play() Button.setTitle("呼び出し中!", for: UIControlState()) } } // 音楽再生が成功した時に呼ばれるメソッド func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { Button.setTitle("ベルを押してください!", for: UIControlState()) } }

LogViewController

// // LogViewController.swift // office_alerm // // Created by wdm_zen on 2017/06/23. // Copyright © 2017年 wdm_zen. All rights reserved. // import UIKit class LogViewController: UIViewController,UITableViewDataSource { @IBOutlet weak var reserved: UITableView! @IBOutlet weak var nonreserved: UITableView! @IBOutlet weak var delivery: UITableView! @IBOutlet weak var tableview: UITableView! //部活配列 var dataList:[String] = [] //txtファイルの保存先 var userPath:String! let fileManager = FileManager() override func viewDidLoad() { super.viewDidLoad() do { //ユーザーが保存したtxtファイルのパス userPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/reserved.txt" let path = userPath if(fileManager.fileExists(atPath: path!) == false){ //ユーザーが保存したtxtファイルが無い場合は、初期txtファイルから読み込む。 // path = Bundle.main.path(forResource: "reserved", ofType: "txt")! } //txtファイルのデータを取得する。 let txtData = try String(contentsOfFile:path!, encoding:String.Encoding.utf8) //改行区切りでデータを分割して配列に格納する。 dataList = txtData.components(separatedBy: "\n") //テーブルビューを編集モードにする。 // reservedTableview.isEditing = true //txtファイルの出力先を確認する。 print(userPath) } catch { print(error) } // Do any additional setup after loading the view. } //データを返すメソッド func tableView(_ tableView:UITableView, cellForRowAt indexPath:IndexPath) -> UITableViewCell { //セルを取得する。 let cell = tableView.dequeueReusableCell(withIdentifier: "tablecell_reserved", for:indexPath as IndexPath) as! VisitedTableViewCell //カンマでデータを分割して配列に格納する。 let dataDetail = dataList[indexPath.row].components(separatedBy: ",") //セルのラベルに部名、部室を設定する。 cell.name.text = dataDetail[0] // cell.time.text = "時間:" + dateString(date: dataDetail[1]) cell.time.text = "時間:" + dataDetail[1] return cell } //データの個数を返すメソッド func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int { return dataList.count } //テーブルビュー編集時に呼ばれるメソッド func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { //削除の場合、配列からデータを削除する。 if( editingStyle == UITableViewCellEditingStyle.delete) { dataList.remove(at: indexPath.row) } //テーブルの再読み込み tableView.reloadData() //CSVファイルにデータを保存する。 savetxt() } //CSVファイル保存メソッド func savetxt() { //改行区切りで部活配列を連結する。 let outputStr = dataList.joined(separator: "\n") do { if(outputStr == "") { //部活配列が空の場合はユーザーが保存したCSVファイルを削除する。 try fileManager.removeItem(atPath: userPath) } else { //ファイルを出力する。 try outputStr.write(toFile: userPath, atomically: false, encoding: String.Encoding.utf8 ) } } catch { print(error) } } 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }

VisitedTableViewCell

// // VisitedTableViewCell.swift // office_alerm // // Created by wdm_zen on 2017/06/26. // Copyright © 2017年 wdm_zen. All rights reserved. // import UIKit class VisitedTableViewCell: UITableViewCell { @IBOutlet weak var name: UILabel! @IBOutlet weak var time: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

fuzzball

2017/06/26 08:40

let dataDetail = dataList[...の下にprint(dataDetail)を追加して、要素が2つ以上あるかどうか確認して下さい。
JunZenpou

2017/06/26 08:46

print(dataDetail)を追加して、要素は、このようになりました。["予約済み", "2017/06/26 16:11:51"] ["予約済み", "2017/06/26 16:11:56"] ["予約済み", "2017/06/26 16:12:01"] ["予約済み", "2017/06/26 16:12:07"] [""]
JunZenpou

2017/06/26 08:47

最後だけ空の[""]になっているのも、わからないです。
Bongo

2017/06/26 08:51

fuzzballさんのご指摘に加え、cellのtimeとラベルの接続状況も気になります。ストーリーボードのコネクションインスペクタはどのような状態でしょうか?
fromageblanc

2017/06/26 08:52 編集

元ネタのテキストデータの最後に改行コードが入ってるんでしょ。きっと。
guest

回答1

0

ベストアンサー

swift

1dataList = txtData.components(separatedBy: "\n")

swift

1dataList = txtData.components(separatedBy: "\n").filter {!$0.isEmpty}

に変更してみて下さい。
これで、改行のみの行をスキップします。

もしくは、tableView(_:cellForRowAt:)の中で要素が足りないときの処理を入れるか。

投稿2017/06/26 09:00

fuzzball

総合スコア16731

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

JunZenpou

2017/06/26 09:06

上手くいきました。ありがとうございます!!!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問