Objective-CからSwiftへの変換メモ その5
Xcodeに任せてできたコードが落ちたのでメモして置く。
Objective-Cだと、辞書からメッセージを取り出せる。
- (void)displayAlert:(NSDictionary*)aDictionary { NSAlert *alert = [[NSAlert alloc] init]; [alert addButtonWithTitle:@"OK"]; [alert setMessageText:[aDictionary objectForKey:@"messageText"]]; [alert setInformativeText:[aDictionary objectForKey:@"InformativeText"]]; [alert beginSheetModalForWindow:[[NSApplication sharedApplication] mainWindow] completionHandler:^(NSModalResponse returnCode) { }]; }
上記コードをobjc2swiftで変換し、さらにXcodeの修正要求を反映したものが以下。
func displayAlert(aDictionary: Dictionary) { let alert = NSAlert() alert.addButton(withTitle: "OK") alert.messageText = aDictionary["messageText"]! alert.informativeText = aDictionary["informativeText"]! alert.beginSheetModal(for: self.view.window!, completionHandler: { (returnCode: NSApplication.ModalResponse) in } )}
動作させ見たら、lldbが起動してアプリが落ちた。
エラーの内容は「Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value」
そう言われても分からないので、ネットを漁って分かった動作するコードが以下。辞書は使ってない。
func displayAlert(question: String, text: String) { let alert = NSAlert() alert.addButton(withTitle: "OK") alert.messageText = question alert.informativeText = text alert.beginSheetModal(for: self.view.window!, completionHandler: { (returnCode: NSApplication.ModalResponse) in }) return }
動作するコードを見つけたので逃げてしまったが、どうやらDictionary経由で値を渡すとnilが入り、nilをアンラップしようとして落ちることまでは突き止めた。何故String型引数を二つ持つと良くてDictionaryだとあかんのか良く分からん。誰か教えて!
この投稿へのトラックバック
トラックバックはありません。
- トラックバック URL
この投稿へのコメント