3

I used realm.io in swift. I have 6 and more data. I wanna select random 4 data.

var words: Results<Word> {
    get {
        return Realm().objects(Word).filter("Limit(4)")
    }
}
Zombo
  • 1
  • 62
  • 391
  • 407

4 Answers4

2

Swift 2

Here is my attempt to create a random function.

In my case, I had to retrieve a random image from Realm DB and display it. So I made a static function in the Image class.

class Image: Object {
    dynamic var filename = ""

    static func randomImage() -> Image? {
        let images = uiRealm.objects(Image)
        if images.count == 0 {
            return nil
        }
        let index = Int(arc4random_uniform(UInt32(images.count)))
        return images[index]
    }
}

//Get a random image
Image.randomImage()

As for the limit function, I don't really see the necessity for it, but here is a possible way to do it:

class Image: Object {
    dynamic var filename = ""
    
    static func limitImages(limit: Int) -> [Image]? {
        let images = uiRealm.objects(Image)
        if images.count == 0 {
            return nil
        }
        var limitImages: [Image] = []
        for iter in 0..<limit {
            if images.count < iter {
                break
            } else {
                limitImages.append(images[iter])
            }
        }
        return limitImages
    }
}

//Get 5 images
Image.limitImages(5)

You can use these functions as a Realm extension doing something like this:

extension Realm {
    func random(type: Object.Type) -> Object? {
        let objects = uiRealm.objects(type)
        if objects.count == 0 {
            return nil
        }
        let index = Int(arc4random_uniform(UInt32(objects.count)))
        return objects[index]
    }
}

//Get a random Animal
let myRealm = try! Realm()
myRealm.random(Animal)

Or the result object version

extension Results {
    func random() -> T? {
        if self.count == 0 {
            return nil
        }
        let index = Int(arc4random_uniform(UInt32(self.count)))
        return self[index]
    }
}

//Get a random row from any Object
let randomObject = myRealm.objects(Person).random()
Community
  • 1
  • 1
Kalzem
  • 7,320
  • 6
  • 54
  • 79
1

Get limited realm results as array:

You could basically create extension to Results(predefined class from Realm library) like this:

import RealmSwift
import ObjectMapper


extension Results{

    func get <T:Object> (offset: Int, limit: Int ) -> Array<T>{
        //create variables
        var lim = 0 // how much to take
        var off = 0 // start from
        var l: Array<T> = Array<T>() // results list

        //check indexes
        if off<=offset && offset<self.count - 1 {
            off = offset
        }
        if limit > self.count {
            lim = self.count
        }else{
            lim = limit
        }

        //do slicing
        for i in off..<lim{
            let dog = self[i] as! T
            l.append(dog)
        }

        //results
        return l
    }
}

and then usage would be something like this:

let realm = try! Realm()
realm.objects(NewsDb).filter("homepageCategory = 1").get(0, limit: 5)

ps. This is temporary solution. Optimization would be if you replace for-loop for doing slicing for some functional Swift function...

Elvis Rudonja
  • 389
  • 3
  • 5
0

Realm does not currently support limiting directly, but you could generate 4 random integers in the range 0..<wordCount and use those to index into the results?

segiddins
  • 4,110
  • 1
  • 17
  • 22
0

Realm does not support random object picking but you can use this function called randomElement() which will return a random object from given list. the method will return nil if the list is empty. Source => https://developer.apple.com/documentation/swift/array/2994747-randomelement

for picking up specific number of objects above answers will work

Gulfam Khan
  • 1,010
  • 12
  • 23