对象已被删除或失效

时间:2016-07-01 15:40:20

标签: swift realm

这个问题已被列出很多,但我看不到符合我情景的问题。我有一个功能来添加和删除喜欢的音乐。我可以先添加它,也可以删除它。但在我再次添加之后。繁荣!!!请有人帮帮我。谢谢!

错误抛出如下:

***由于未捕获的异常终止应用' RLMException',原因:'不允许将已删除或无效的对象添加到域中

请帮助我查看以下代码:

func addMusicToFavorite(music: Music) {
    let realm = try! Realm()

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

}

func removeMusicFromFavorite(music: Music) {
    //Tips: '\(musics.mId)' : put quote ' ' like this means String, if not it will treat it as Int
    let realm = try! Realm()
    let tmpMusic = realm.objects(Music.self).filter("_mId == '\(music.mId)'")
    try! realm.write {
        print("remove \(music.mId)")
        realm.delete(tmpMusic)
    }
}

我的音乐模特:

class Music: Object {

private dynamic var _mId: String!
private dynamic var _mTitle: String!
private dynamic var _mArtist: String!
private dynamic var _mThumbnail: String!
private dynamic var _mAlbumImg: String!
private dynamic var _mPath: String!
private dynamic var _mNumOfView: String!
private dynamic var _mDuration: String!

var mId: String {
    return _mId
}

var mTitle: String {
    return _mTitle
}

var mArtist: String {
    return _mArtist
}

var mAlbumImg: String {
    return _mAlbumImg
}

var mThumbnail: String {
    return _mThumbnail
}

var mPath: String {
    return _mPath
}

var mNumOfView: String {
    return _mNumOfView
}

var mDuration: String {
    return _mDuration
}

required init() {
    super.init()
}

required init(realm: RLMRealm, schema: RLMObjectSchema) {
    super.init(realm: realm, schema: schema)

// fatalError(" init(realm:schema :)尚未实现")     }

required init(value: AnyObject, schema: RLMSchema) {
    super.init(value: value, schema: schema)

// fatalError(" init(value:schema :)尚未实现")     }

override static func primaryKey() -> String? {
    return "_mId"
}


convenience init(dict: Dictionary<String, AnyObject>) {
    self.init()

    if let id = dict["id"] as? String {
        self._mId = id
    }

    if let titleAndArtist = dict["music_title"] as? String {
        let tmp = Utils.instance.splitStringsWithCharacter(titleAndArtist)
        self._mTitle = tmp.title
        self._mArtist = tmp.artist            
    }

    if let thumbnail = dict["image_thumb"] as? String {
        self._mThumbnail = thumbnail
    }

    if let albumImg = dict["image_album"] as? String {
        self._mAlbumImg = albumImg
    }

    if let path = dict["music_path"] as? String {
        self._mPath = path
    }

    if let numOfView = dict["music_view"] as? String {
        self._mNumOfView = numOfView
    }

    if let duration = dict["music_duration"] as? String {
        self._mDuration = duration
    }

}

}

1 个答案:

答案 0 :(得分:5)

仅针对记录,因为答案隐藏在所有评论中:从领域中删除后,您无法重新add 相同的对象实例。 / p>

realm.add持久存在给定的对象。数据库中的此调用直接在磁盘上而不是在普通内存中进行管理。

但是如果你保留非托管对象并使用realm.create(object)在Realm中创建一个副本,你可以重复这一点,即使删除了以这种方式创建的对象。