领域:删除特定对象

时间:2017-01-06 15:27:05

标签: react-native realm

我正在使用react native开发应用程序,我需要删除特定对象,这些对象在过滤方法中给我但是它给了我一个名为

的错误

"只能删除交易中的对象。"

这是我的代码

allObj1 = {
                id : 1,
                speed : "1",
                accuracy: "100",
                bearing: "1",
                longitude: "192",
                altitude: "1111",
                latitude: "1111",
                time: "11111",
                locationProvider: "2222",
            };

        allObj2 = {
                id : 2,
                speed : "1",
                accuracy: "100",
                bearing: "1",
                longitude: "192",
                altitude: "1111",
                latitude: "1111",
                time: "22222",
                locationProvider: "2222",
            };

        allObj3 = {
                id : 3,
                speed : "1",
                accuracy: "100",
                bearing: "1",
                longitude: "192",
                altitude: "1111",
                latitude: "1111",
                time: "333333",
                locationProvider: "2222",
            };

        realm.write(() => {
            realm.create('Location',allObj1 );          
            //realm.delete(firstObj);
            realm.create('Location',allObj2 );
            realm.create('Location',allObj3 );
        });         

        let locationO = realm.objects('Location');
        //let tanlocation = locationO.filtered('id >1 AND id <3 ');
        // Observe Collection Notifications         

        realm.objects('Location').filtered('id >=1 AND id <=3').addListener((tanlocation, changes) => {

            try{
                tanlocation.forEach((realmObj,index) => {                           
                    realm.delete(realmObj);             
                });
            }
            catch(err){
                console.log(err);
            }
        });


        // Unregister all listeners
        realm.removeAllListeners();

        //realm.delete(tanlocation);
        //console.log( tanlocation );

        console.log(locationO);

它抛出了一个名为&#34的错误;只能删除事务中的对象。&#34;

是谁都遇到过这种问题?任何人都知道如何修复这个或替代方法来实现所提到的功能

1 个答案:

答案 0 :(得分:3)

要将删除包装在realm.write中,就像使用realm.create一样。

realm.write(() => {
    realm.delete(realmObj)
})

当我遇到这个问题时,这对我有用。只有在我读完Github comment

后才能实现