Fetching with a certain number and some offset with Realm(https://realm.io/)

1.5k views Asked by At

I am trying to turn to Realm(https://realm.io/) and come across a problem. If we are handling a data base storing a large number of records, and we just want to fetching a certain number of records from some offset, how can we get it with realm. you know, it can be easily done by sql or core data. and we don't want to fetch it all from the data base and then caculate ourselves in the memory, as it needs much time

1

There are 1 answers

2
jpsim On

Since Realm reads data from the disk upon access (even down to the property level), you don't have to worry about reading more from disk than is necessary. So if you want to only access the next 10 objects after the 100th, you just have to skip accessing the first 100.

For example:

let realm = Realm()
let modelObjects = realm.objects(MyModel) // => Say there are 1000 items
for i in 100..<110 {
  let itemAtIndex = modelObjects[i] // => Inferred to be of type `MyModel`
  itemAtIndex.someProperty // => Only at this point is data *just for that property* read from disk
  // Perform operations in memory here...
}
// At this point, only 10 objects were ever read from disk
// and only the properties on those objects that were accessed.

I'm using Realm Swift in this example, but the same concepts apply to Realm Objective-C.