【发布时间】:2016-02-11 19:06:16
【问题描述】:
背景:
我对 Swift 非常陌生,但总的来说也是编程,所以提前道歉。我唯一真正的数据库体验是 MySql,即使它不是那么热门。
我正在通过构建一个基本的目标/习惯跟踪应用来学习 Swift + Realm。
任务:
我有一个目标对象,其中包含一个名为“id”的主键。目标可能是“减肥”。我还有一个 Streak 对象,其中包括 7 次每日“签到”。用户设定目标,每天签到。
每个目标可以有多个“连续”,例如在一个 7 天的冲刺/连续冲刺之后,用户可以开始另一个。你也可以有多个目标。为了实现这一点,我试图复制目标的自动递增 ID 的功能,这也是一个主键。这也将记录在相应的条纹中。
我的问题:
我遇到的问题是,当我尝试存储另一个目标时,出现错误:
*** Terminating app due to uncaught exception 'RLMException', reason: 'Primary key can't be changed after an object is inserted.'
这是我的 AddGoalController 中的代码。我添加了 cmets 来解释我的想法。
import UIKit
import RealmSwift
class AddGoalController: UIViewController {
//set default ID for next goal object
var newID = 1
//function to determine what the next ID needs to be.
func getNextID() -> Int{
let realm = try! Realm()
let currentGoal = realm.objects(Goal)
//gets maximum ID in the Goal object
let id = currentGoal.max("id") as Int?
let goal = id != nil ? currentGoal.filter("id == %@", id!).first : nil
//figure if the query is empty, e.g. no goals at all. If it is not, increment the newID.
if(goal != nil) {
newID = goal!.id++
}
print(newID)
return newID
}
//if a button is pressed...
@IBAction func goalButton(sender: UIButton) {
// Generate the newID
getNextID()
let goalObj = Goal()
goalObj.id = newID
goalObj.Title = setGoal.text!
goalObj.Aim = ""
goalObj.Action = setHabit.text!
goalObj.Active = 1
// Get the default Realm
let realm = try! Realm()
// You only need to do this once (per thread)
// Add to the Realm inside a transaction
try! realm.write {
realm.add(goalObj, update: true)
}
事实上,即使我在按钮中注释了所有内容并且只有 getNextID(),我仍然会遇到同样的错误。
我的问题是:
1. 有没有更优雅的方式来实现我的目标,即拥有一个或多个目标并附有多个条纹。只有最新的连胜是活跃的。
2。是什么导致了这个错误?
在此先感谢
【问题讨论】: