将对象存储到RealmSwift中的List后EXC_BAD_ACCESS

时间:2017-05-14 17:33:07

标签: ios swift list swift3 realm

我将数据存储到Realm中,我在游戏对象中有一个目标列表:

Goal.swift

class Goal : Object {
    dynamic var scoreTime = Date()
    dynamic var scoreBy:Player?
    dynamic var scoreForTeam:GameTeam?
    dynamic var homeScoreAfter:Int = 0
    dynamic var awayScoreAfter:Int = 0
    let passers = List<Player>()
}

Game.swift

class Game : Object {
    dynamic var startDate:Date? = nil
    dynamic var endDate:Date? = nil
    dynamic var homeTeam:GameTeam?
    dynamic var awayTeam:GameTeam?
    let goals = List<Goal>()
}

我在Game的目标属性中添加了一个目标,但是在保存发生后,目标列表似乎无效。这是代码:

let toCreate = Game()

toCreate.homeTeam = GameTeam()
toCreate.awayTeam = GameTeam()

toCreate.startDate = Date()

let goal = Goal(scoreBy: allPlayers[0].player, scoreForTeam: toCreate.homeTeam!, passedBy: [], scoreTime: Date(), homeScoreAfter: 1, awayScoreAfter: 0)
toCreate.goals.append(goal)

let realm = try! Realm()

try! realm.write {
    realm.add(toCreate)
}

但是在realm.write电话之后我遇到了这个错误:

(lldb) po toCreate.goals

expression produced error: error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=1, address=0x8).
The process has been returned to the state before expression evaluation.

我不能再消耗目标列表了。它在realm.write完成之前打印正常。我在这里找不到一些微不足道的东西......?对象的其他部分播放得很好。

编辑:所以不知何故问题是属性Goal.passers - 从对象中删除它可以解决问题。这可能与对象层次结构中有很多对玩家的引用有关吗?请参阅Game.homeTeam.playersGoal.scoreByGoal.passers,其中包含对玩家对象的引用。

1 个答案:

答案 0 :(得分:1)

需要回答我自己的问题。我的问题出现在Goal - 对象的自定义初始化代码中,如下所示:

    init(scoreBy:Player, scoreForTeam:GameTeam, passedBy:[Player]?, scoreTime:Date, homeScoreAfter:Int, awayScoreAfter:Int) {
        super.init()
        ... 
    }

此代码不会生成可正常工作的域对象。没有自己的init方法内联创建Goal - 对象解决了这个问题。

编辑:行为本身很奇怪 - 该构造函数是否有效,或者这是Realm中的错误?