初心者です。
あるViewControllerにおいてRealmにデータをvalue: ["userID": client.restext]として保存しました。client.restext は文字列です。下のようなコードです。保存はきちんとできています。
Swift
1do { 2 let realm = try Realm() 3 let person = [realmDataSet(value: ["userID": client.restext])] 4 try! realm.write { 5 realm.add(person) 6 print("OK", person) 7 } 8 } catch{ 9 print("error") 10 } 11 }
この保存したデータを別のViewControllerでボタンを押したらLabelが出て来て、Label.文字を出したいです。
Swift
1import Foundation 2import RealmSwift 3class realmDataSet: Object { 4 5 @objc dynamic var userID = "" 6 @objc dynamic var coupon = "" 7 @objc dynamic var result = "" 8} 9import UIKit 10import RealmSwift 11class InformationViewController: UIViewController { 12 13 @IBOutlet weak var seeUserID: UIButton! 14 @IBOutlet weak var myUserID: UILabel! 15 16 17 18 19 let realm = try! Realm() 20 21 override func viewDidLoad() { 22 super.viewDidLoad() 23 24 // Do any additional setup after loading the view. 25 /* print("データ設定前のtotalData:", totalData) 26 // まずデータを作る 27 if totalData.count == 0 { 28 let array = userID // 個数?中身がわからなかったので配列と想定しました。 29 try! realm.write { 30 for n in 0 ... array.count - 1 { 31 let data = RealmData() // まずRealmDataのインスタンスを作る 32 data.userID = array[n] //それぞれの要素に中身を詰める 33 // ~ここで他の要素必要なら登録~ 34 realm.add(data) //そして保存する 35 } 36 37 } 38 print("データ設定後のtotalData:", totalData) 39 } 40 */ 41 } 42 43 @IBAction func seeUserID(_ sender: Any) { 44 /*for n in 0 ... self.totalData.count - 1 { 45 let data = self.totalData[n] // 各データからインスタンス作る 46 print(data.userID) // 必要なものを取り出す。 47 }*/ 48 // let person = [realmDataSet(value: ["userID"])] 49 let person = try! realm.objects(realmDataSet.self) 50 51 // Realmに保存されているTodo型のobjectsを取得。 52 53 self.myUserID.text = person.userID 54 } 55 56 57 /* 58 // MARK: - Navigation 59 60 // In a storyboard-based application, you will often want to do a little preparation before navigation 61 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 62 // Get the new view controller using segue.destination. 63 // Pass the selected object to the new view controller. 64 } 65 */ 66 67} 68 69
あなたの回答
tips
プレビュー