【发布时间】:2016-01-15 11:45:16
【问题描述】:
我对 Sqlite 非常熟悉,但我决定在我的下一个项目中尝试使用领域。 我在从数据库读取数据和删除对象时遇到问题 也是。
我正在使用默认领域路径:
let realm = RLMRealm.defaultRealm()
当按下按钮时,应该添加或删除 RLMObject(如果已经存在)。这是按钮的 IBAction:
@IBAction func addToFavor(sender: UIBarButtonItem) {
// Create RealmTV (RLMObject)
let tvShow = RealmTV(id: id, title: TitleLabel.text!, posterPath: posterUrl)
if favoriteButton.image!.isEqual(UIImage(named: "Favor unfilled")) {
realm.beginWriteTransaction()
// Create or update tv-show in database
RealmTV.createOrUpdateInDefaultRealmWithValue(tvShow)
try! realm.commitWriteTransaction()
// Change button state
favoriteButton.image = UIImage(named: "Favor filled")
}
else
{
realm.beginWriteTransaction()
// Delete tv-show object from database
realm.deleteObject(tvShow) /* RLMException here */
try! realm.commitWriteTransaction()
// Change button state
favoriteButton.image = UIImage(named: "Favor unfilled")
}
}
当我将对象添加到 db 后尝试删除它时。我得到一个 RLMExecption 说:
'只能从它所属的 Realm 中删除一个对象。'
我明白上述原因是什么意思,但不知道如何解决?
还有如何在添加后仅从 db 中检索此对象?
编辑
这是我的 RealmTv 课程:
import UIKit
import Realm
class RealmTV: RLMObject {
dynamic var id = ""
dynamic var title = ""
dynamic var posterPath = ""
override class func primaryKey() -> String? {
return "id"
}
override init() {
super.init()
}
init(id: String, title: String, posterPath: String) {
super.init()
self.id = id
self.title = title
self.posterPath = posterPath
}
}
【问题讨论】:
-
我看到你正在使用 Swift 的 Realm Objective-C 接口。在大多数情况下,建议在 Swift 应用程序中使用 Realm Swift。您这样做是因为您需要在 iOS 7 上运行,还是需要同时从 Swift 和 Objective-C 访问您的 Realm 模型?
-
我需要iOS 7+的支持所以我认为有必要使用Objective-C接口
标签: ios database swift swift2 realm