2016-12-05 107 views
6

我有从JSON响应保存列表的领域对象。但是现在我需要删除该对象,如果该对象不再从JSON列表中。我该怎么做? 这是我的init的境界迅速从领域删除对象

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

你可能婉t检查[领域链接](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)