###前提・実現したいこと
Realmにあらかじめデータが入っている前提でループ処理をしてRealmにあるデータを取り出した後に再度Realmにデータを一部だけ戻したい。
###発生している問題・エラーメッセージ
再度Realmにデータを格納する際に、2個目以降のデータを格納するとエラーが発生する。 ↓エラーコード Terminating app due to uncaught exception 'RLMException', reason: 'Primary key can't be changed after an object is inserted.'
###該当のソースコード
swift
1import UIKit 2import RealmSwift 3 4class ViewController: UIViewController { 5 6 // Realm名前データ格納配列 7 var realmname:[String] = [] 8 var id:Int = 1 9 10 override func viewDidLoad() { 11 super.viewDidLoad() 12 // Do any additional setup after loading the view, typically from a nib. 13 } 14 15 override func didReceiveMemoryWarning() { 16 super.didReceiveMemoryWarning() 17 // Dispose of any resources that can be recreated. 18 } 19 20 // ボタン押下後の処理 21 @IBAction func tapButton(_ sender: Any) { 22 let config = Realm.Configuration(deleteRealmIfMigrationNeeded: true) 23 Realm.Configuration.defaultConfiguration = config 24 25 let realm = try! Realm() 26 27 // Realmにある名前をrealmnameに寄せておく 28 while true { 29 if let playerbefore = realm.object(ofType: PlayerTable.self, forPrimaryKey: id as AnyObject) 30 { 31 realmname.append(playerbefore.name) 32 id += 1 33 }else{ 34 break 35 } 36 } 37 38 // Realmデータ全削除 39 try! realm.write { 40 realm.deleteAll() 41 } 42 43 let playerafter:PlayerTable = PlayerTable() 44 id = 0 45 46 // realmnameに寄せた名前を再度Realmに格納 47 try! realm.write { 48 while true { 49 if realmname[id + 1] == "" { 50 break 51 } 52 playerafter.id = id + 1 // 2回目のループでここに来たときにエラーになる 53 playerafter.name = realmname[id] 54 realm.add(playerafter, update: true) 55 id += 1 56 } 57 } 58 } 59}
swift
1import Foundation 2import RealmSwift 3 4class PlayerTable: Object { 5 6 dynamic var id = Int() 7 dynamic var name = String() 8 dynamic var point = Int() 9 10 // nameをプライマリキーに設定 11 override static func primaryKey() -> String? { 12 return "id" 13 } 14}
###補足情報(言語/FW/ツール等のバージョンなど)
Swift 3.1
Realm 1.2.1
回答1件
あなたの回答
tips
プレビュー