使用50条记录限制执行FILO记录插入RealmSwift

时间:2015-12-16 03:24:29

标签: ios swift realm

我有NotificationList对象,它使用tableView显示许多通知数据。

import RealmSwift

class NotificationList: Object {
    dynamic var title = ""
    dynamic var body = ""
    dynamic var createdAt = NSDate()
    let notifications = List<Notification>()
}

每次我插入记录时,都会使用RealmSwift运行此功能。

func insertNotification(list: NotificationList){
        try! realm.write({ () -> Void in
            realm.add(list)
        })
}

但是,我真正需要帮助的是,我想检查NotificationList Realm对象的所有总数,然后在通知进入时随时插入记录。在我检查总计数后,我想删除如果总计数超过50 **(计数<= 50)**使用 FILO(先进先出) createdAt sorting

每次插入新记录时如何进行realmSwift查询的帮助?我是RealmSwift的新手。我现在只能做CRUD因为我是初学者。

3 个答案:

答案 0 :(得分:3)

更简洁的替代方案:

func insertNotification(list: NotificationList) {
    // Insert the new list object
    try! realm.write { 
        realm.add(list)
    }

    // Trim the number of objects back down to 50, keeping the newest objects.
    let sortedLists = realm.objects(NotificationList).sorted("createdAt")
    if sortedLists.count > 50 {
        try! realm.write {
            realm.delete(sortedLists.prefix(sortedLists.count - 50))
        }    
    }
}

答案 1 :(得分:2)

你走在正确的轨道上。 :)

Realm有一个非常有用的功能,即查询结果随着基础数据的修改而动态更新,因此,迭代现有的通知列表列表并删除旧的通知列表非常简单直到计数再次降至50。

func insertNotification(list: NotificationList){
    // Insert the new list object
    try! realm.write { 
        realm.add(list)
    }

    // Iterate through all list objects, and delete the earliest ones
    // until the number of objects is back to 50
    let sortedLists = realm.objects(NotificationList).sorted("createdAt")
    while sortedLists.count > 50 {
        let first = sortedLists.first
        try! realm.write {
            realm.delete(first)
        }    
    }
}

让我知道你怎么去!

答案 2 :(得分:1)

您需要获取NotificationList对象的计数,然后需要删除任何多余的对象,如果它们的计数大于或等于50,再加上一个对象被插入。您需要删除旧对象。以下是可以帮助您的实现。

func insertNotification(list: NotificationList){

  //Check if there are more than 50 notifications lists already we want
  //to delete all items in access of 50 plus one more to accommodate
  //the new  object being inserted.

  let sortedItems = realm.objects(NotificationList).sorted("createdAt")

  while sortedItems.count >= 50 {
    let first = sortedItems.first
    try! realm.write {
      realm.delete(first)
    }
  }


  //Now add the new object
  try! realm.write({ () -> Void in
    realm.add(list)
  })
}
相关问题