2016-12-05 10 views
6

JSON Responseからリストを保存するRealmオブジェクトがあります。しかし、オブジェクトがJSONから再びリストにない場合は、オブジェクトを削除する必要があります。それはどうやって? これは、レルムのための私のinitSwiftオブジェクトをRealmから削除

func listItems (dic : Array<[String:AnyObject]>) -> Array<Items> { 
     let items : NSMutableArray = NSMutableArray() 
     let realm = try! Realm() 
     for itemDic in dic { 
      let item = Items.init(item: itemDic) 
       try! realm.write { 
        realm.add(item, update: true) 
       } 
      items.addObject(item) 
     } 
     return NSArray(items) as! Array<Items> 
} 
+0

に含まれていないすべての項目を照会することができところで私はあなたがワンかもしれないitem.id – Voyager

+0

の主キーを持っています削除方法について[realm link](https://realm.io/docs/swift/latest/#deleting-objects)を確認してください –

答えて

3

でレルム内のオブジェクトの削除について

リアより多くのあなたが挿入されているオブジェクトに主キーを割り当て、新しい解析されたJSONを受信したときに、そのキーがすでに以前に存在するかどうかを確認していますそれを追加する。

class Items: Object { 
    dynamic var id = 0 
    dynamic var name = "" 

    override class func primaryKey() -> String { 
     return "id" 
    } 
} 

新しいオブジェクトを挿入する場合は、まずRealmデータベースにクエリが存在するかどうかを照会します。

let repeatedItem = realm.objects(Items.self).filter("id = 'newId'") 

if !repeatedItem { 
    // Insert it 
} 
14

あなたItemsオブジェクトはidプロパティを持っており、あなたが新しいセットに含まれていない古い値を削除したい場合は、どちらかあなただけの

let result = realm.objects(Items.self) 
realm.delete(result) 

ですべてのものを削除してから、すべての項目を追加することができます想像再び王国、 またはあなたにも新しいセット

let items = [Items]() // fill in your items values 
// then just grab the ids of the items with 
let ids = items.map { $0.id } 

// query all objects where the id in not included 
let objectsToDelete = realm.objects(Items.self).filter("id NOT IN %@", ids) 

// and then just remove the set with 
realm.delete(objectsToDelete) 
関連する問題