swift初学者です。
初めてapplewatchのアプリを開発しているのですが、つまづいてしまったので相談させて下さい。
タイトルの通り、watchOSでのuserDefaultsによるデータの保存についてご教授いただきたいです。
iOSアプリでuserDefaultsを使用することはできたのですが、それをそのままwatchOSに流用した際に、
Attempt to insert non-property list object
とのエラーメッセージが出ました。
プロパティにないオブジェクトをuserDfaultsに挿入した際に出るエラーメッセージみたいですが、どう解決すればいいかわかりません。
実現したいと思っているアプリは、ボタンを押すと、ボタンを押した時の時間を記録するアプリです。
修正ボタンを押したら、記録した時間を消去するようにしたいです。
userDefaultsのコードを入れる前はエラーメッセージが出ることなく機能しました。
現在のコードは下記のとおりです。
import WatchKit import Foundation import UIKit class InterfaceController: WKInterfaceController { //データフォマッターインスタンス let formatter = DateFormatter() //ラベル @IBOutlet weak var timeLabelWatch1: WKInterfaceLabel! //ボタンアウトレット @IBOutlet weak var theTimeButtonWatch1: WKInterfaceButton! //記録ボタン @IBAction func timeButtonWatch1() { let date = Date() self.timeLabelWatch1.setText(formatter.string(from:date )) UserDefaults.standard.set(self.timeLabelWatch1 , forKey:"date1") UserDefaults.standard.synchronize() self.theTimeButtonWatch1.setEnabled(false) self.theCancelButtonWatch1.setEnabled(true) } //修正ボタン @IBAction func cancelButtonWatch1() { //ダイアログ表示 let okButtonAction1 = WKAlertAction(title:"OK" , style: .default ){() -> Void in self.timeLabelWatch1.setText("-----時間-----") UserDefaults.standard.set(self.timeLabelWatch1 , forKey:"date1") UserDefaults.standard.synchronize() self.theTimeButtonWatch1.setEnabled(true) self.theCancelButtonWatch1.setEnabled(false) } let cancelButtonAction1 = WKAlertAction(title:"キャンセル" , style: .default ){() -> Void in } presentAlert(withTitle: "時間を消去します", message: "消去してよろしいですか?", preferredStyle: .alert, actions: [okButtonAction1, cancelButtonAction1]) } override func awake(withContext context: Any?) { super.awake(withContext: context) // Configure interface objects here. //データフォーマッターの設定 formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "MdHms", options: 0, locale: Locale(identifier: "ja_JP")) //UserDefaults設定 let userDefaults = UserDefaults.standard //userDefaultsの初期設定 userDefaults.register(defaults: ["date1" : "-----時間-----"]) timeLabelWatch1.setText(UserDefaults.standard.string(forKey: "date1")) //修正ボタン初期設定 self.theCancelButtonWatch1.setEnabled(false) } override func willActivate() { // This method is called when watch view controller is about to be visible to user } override func didDeactivate() { // This method is called when watch view controller is no longer visible } }
コードは以上になります。
シミュレーターで記録ボタンを押下した際に
Attempt to insert non-property list object
のエラーメッセージが出てしまいます。
調べてみると、NSUserDefaultで保持できる型は、NSString型、NSNumber型、NSArray型、NSDictionary型、 NSData型、NSDate型のみと書かれていたのですが、
現在のコードではString型として保存はできないのでしょうか?
iOSアプリに関する記事は多く見つけれたのですが、watchOSに関する記事が非常に少なくて困っています。
解決方法をご教授いただきたいです。
よろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー