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

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

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

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

Q&A

解決済

1回答

2136閲覧

Deleteするとクラッシュしてしまう。

ZY.

総合スコア22

Swift

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

0グッド

0クリップ

投稿2019/02/28 13:47

前提・実現したいこと

タスク管理するアプリを例にRealmの勉強しています。
Deleteをする際の通知機能の実装をしているのですが、Deleteをするとアプリがクラッシュしてしまう。
原因はどのように調べることができますか?
原因の調べ方とその原因を知りたいです。
Thread 1: signal SIGABRTAppDelegate.swiftに表示されるのはOutletが繋がっていないということであっていますか?

回答よろしくおねがいします。

発生している問題・エラーメッセージ

AppDelegate.swift
Thread 1: signal SIGABRT

該当のソースコード

Swift

1AppDelegate.swift 2 3import UIKit 4import UserNotifications 5 6@UIApplicationMain 7class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { 8 9 var window: UIWindow? 10 11 12 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 13 // Override point for customization after application launch. 14 15 let center = UNUserNotificationCenter.current() 16 center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in 17 // Enable or disable features based on authorization 18 } 19 20 center.delegate = self; 21 22 return true 23 } 24 25 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { 26 completionHandler([.sound, .alert]) 27 } 28 29 func applicationWillResignActive(_ application: UIApplication) { 30 // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 31 // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. 32 } 33 34 func applicationDidEnterBackground(_ application: UIApplication) { 35 // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 36 // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 37 } 38 39 func applicationWillEnterForeground(_ application: UIApplication) { 40 // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. 41 } 42 43 func applicationDidBecomeActive(_ application: UIApplication) { 44 // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 45 } 46 47 func applicationWillTerminate(_ application: UIApplication) { 48 // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 49 } 50 51 52} 53

Swift

1ViewController.swift 2 3import UIKit 4import RealmSwift 5import UserNotifications 6 7class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 8 @IBOutlet weak var tableView: UITableView! 9 10 let realm = try! Realm() 11 12 var taskArray = try! Realm().objects(Task.self).sorted(byKeyPath: "date", ascending: false) 13 14 override func viewDidLoad() { 15 super.viewDidLoad() 16 // Do any additional setup after loading the view, typically from a nib. 17 18 tableView.delegate = self 19 tableView.dataSource = self 20 } 21 22 override func didReceiveMemoryWarning() { 23 super.didReceiveMemoryWarning() 24 // Dispose of any resources that can be recreated. 25 } 26 27 override func prepare(for segue: UIStoryboardSegue, sender:Any?) { 28 let inputViewController:inputViewController = segue.destination as! inputViewController 29 30 if segue.identifier == "cellSegue" { 31 let indexPath = self.tableView.indexPathForSelectedRow 32 inputViewController.task = taskArray[indexPath!.row] 33 } else { 34 let task = Task() 35 task.date = Date() 36 37 let allTasks = realm.objects(Task.self) 38 if allTasks.count != 0 { 39 task.id = allTasks.max(ofProperty: "id")! + 1 40 } 41 42 inputViewController.task = task 43 } 44 } 45 46 override func viewWillAppear(_ animated: Bool) { 47 super.viewWillAppear(animated) 48 tableView.reloadData() 49 } 50 51 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 52 return taskArray.count 53 } 54 55 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 56 57 let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) 58 59 let task = taskArray[indexPath.row] 60 cell.textLabel?.text = task.title 61 62 let formatter = DateFormatter() 63 formatter.dateFormat = "yyyy-MM-dd HH:mm" 64 65 let dateString:String = formatter.string(from: task.date) 66 cell.detailTextLabel?.text = dateString 67 68 return cell 69 } 70 71 func tableView(_tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 72 performSegue(withIdentifier: "cellSegue", sender: nil) 73 } 74 75 func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath)-> UITableViewCellEditingStyle { 76 return .delete 77 } 78 79 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 80 if editingStyle == .delete { 81 82 let task = self.taskArray[indexPath.row] 83 84 let center = UNUserNotificationCenter.current() 85 center.removePendingNotificationRequests(withIdentifiers: [String(task.id)]) 86 87 try! realm.write { 88 self.realm.delete(task) 89 tableView.deleteRows(at: [indexPath], with: .fade) 90 } 91 92 center.getPendingNotificationRequests { (requests: [UNNotificationRequest]) in 93 for request in requests { 94 print("/---------------") 95 print(request) 96 print("---------------/") 97 } 98 } 99 100 try! realm.write { 101 self.realm.delete(self.taskArray[indexPath.row]) 102 tableView.deleteRows(at: [indexPath], with: .fade) 103 } 104 } 105 } 106 107}

Swift

1inputViewController.swift 2 3import UIKit 4import RealmSwift 5import UserNotifications 6 7class inputViewController: UIViewController { 8 @IBOutlet weak var titleTextField: UITextField! 9 @IBOutlet weak var contentsTextView: UITextView! 10 @IBOutlet weak var datePicker: UIDatePicker! 11 12 let realm = try! Realm() 13 var task: Task! 14 15 override func viewDidLoad() { 16 super.viewDidLoad() 17 18 // Do any additional setup after loading the view. 19 let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target:self, action:#selector(dismissKeyboard)) 20 self.view.addGestureRecognizer(tapGesture) 21 22 titleTextField.text = task.title 23 contentsTextView.text = task.contents 24 datePicker.date = task.date 25 } 26 27 override func didReceiveMemoryWarning() { 28 super.didReceiveMemoryWarning() 29 // Dispose of any resources that can be recreated. 30 } 31 32 override func viewWillDisappear(_ animated: Bool) { 33 try! realm.write { 34 self.task.title = self.titleTextField.text! 35 self.task.contents = self.contentsTextView.text 36 self.task.date = self.datePicker.date 37 self.realm.add(self.task, update: true) 38 } 39 40 setNotification(task: task) 41 42 super.viewWillDisappear(animated) 43 } 44 45 func setNotification(task: Task) { 46 let content = UNMutableNotificationContent() 47 48 if task.title == "" { 49 content.title = "(タイトルなし)" 50 } else { 51 content.title = task.title 52 } 53 if task.contents == "" { 54 content.body = "(内容なし)" 55 } else { 56 content.body = task.contents 57 } 58 content.sound = UNNotificationSound.default() 59 60 let calendar = Calendar.current 61 let dateComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: task.date) 62 let trigger = UNCalendarNotificationTrigger.init(dateMatching: dateComponents, repeats: false) 63 64 let request = UNNotificationRequest.init(identifier: String(task.id), content: content, trigger: trigger) 65 66 let center = UNUserNotificationCenter.current() 67 center.add(request) { (error) in 68 print(error ?? "ローカル通知登録 OK") 69 } 70 71 center.getPendingNotificationRequests { (requests: [UNNotificationRequest]) in 72 for request in requests { 73 print("/---------------") 74 print(request) 75 print("---------------/") 76 } 77 } 78 } 79 80 @objc func dismissKeyboard() { 81 view.endEditing(true) 82 } 83 84 /* 85 // MARK: - Navigation 86 87 // In a storyboard-based application, you will often want to do a little preparation before navigation 88 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 89 // Get the new view controller using segue.destinationViewController. 90 // Pass the selected object to the new view controller. 91 } 92 */ 93 94}

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

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

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

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

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

fuzzball

2019/03/01 00:22

Thread 1: signal SIGABRT はエラーメッセージではなく、「止まったよ」って言ってるだけです。 Consoleにエラーメッセージが表示されていないでしょうか?
guest

回答1

0

ベストアンサー

原因の調べ方はfuzzballさんがおっしゃっているとおりです。

原因はほとんど予想ですが、
tableView.deleteRows(at: [indexPath], with: .fade)
の中でtableView側は、本当にソースデータが削除されているかを確認するために
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
を呼び出して(プログラマがミスをしていないか)確認しているようなのです。

今回でいえば、「アイテム数が何も変わっていないのでお前データソース削除しとらんやろ?」という意味で強制停止させられます。

というわけで、deleteRowsを呼び出す前にtaskArrayの要素を削除してください。

あとtableView.deleteRows(at: [indexPath], with: .fade)が二回行われそうな気がするので、
そこら辺がちゃんと意図した通りになっているのかも確認してください。

投稿2019/03/01 01:10

takabosoft

総合スコア8356

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

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

ZY.

2019/03/01 03:36

ありがとうございます、解決できました。 `tableView.deleteRows(at: [indexPath], with: .fade)`が二回実行されていたようです。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問