我有一个领域对象Activity,它包含许多变量,包括领域对象User,Profile和Board。这是对象的声明
class RealmActivity: Object
{
dynamic var user: RealmProfile?
dynamic var noticeId = ""
dynamic var notice: RealmNotice?
dynamic var board: RealmBoard?
dynamic var type = ""
dynamic var date = Date()
dynamic var text = ""
dynamic var commentContent = ""
}
以下是从Class到Realm Object的转换
func cacheActivity(activity: Activity) -> RealmActivity
{
let realm = RealmActivity()
if activity.user != nil {
realm.user = cacheUser(user: activity.user!)
}
if activity.noticeId != nil {
realm.noticeId = activity.noticeId!
}
if activity.notice != nil {
realm.notice = cacheNotice(notice: activity.notice!)
}
if activity.board != nil {
realm.board = cacheBoard(board: activity.board!, tag: "activity")
}
realm.type = activity.type!
realm.date = activity.date!
if activity.text != nil {
realm.text = activity.text!
}
if activity.commentContent != nil {
realm.commentContent = activity.commentContent!
}
return realm
}
这是缓存所有活动的方法。 我首先获取所有已缓存的对象并删除它们。然后我获得更新的活动列表并将它们添加到领域
func cacheAllActivities()
{
let realmCached = realm.objects(RealmActivity.self)
let activities = SessionManager.sharedInstance.dashboard.activities
var realmActivities = [RealmActivity]()
if activities.count > 0 {
try! realm.write()
{
realm.delete(realmCached)
for activity in activities
{
let realmActivity = cacheActivity(activity: activity)
self.realm.add(realmActivity)
realmActivities.append(realmActivity)
}
}
}
}
我正在使用此对象将推送通知保留为手机上的活动。 当我写一个对象时,第一次回到应用程序时,我设法用它的所有对象检索它而没有问题。当我关闭应用程序并再次检索它时,我的对象RealmProfile,RealmNotice和RealmBoard在它们不应为空时返回nil。其余数据存在,只返回对象中的对象。当我多次检索对象时,会发生这种情况。之后它总是零。每次重启后我都不会重写该对象。我已经在这几天了,任何帮助都将不胜感激。
谢谢!