1

I am trying to get the objects from realm, where newDate is later then firstDate. So if the date from firstDate is 05.10.2017, it will get objects after that date, example 06.10.2017, but not 04.10.2017.

This is how I am storing the date:

class User: Object {
    @objc dynamic var firstDate = Date()
    @objc dynamic var newDate = Date()
}

This is how I am saving the objects:

let date = Date()
let realm = try! Realm()
let myUser = User()

myUser.firstDate = self.date

This is how I am trying to retrieve the objects:

var userData: Results<User>?
if (homeIndexPathRow == 0) {
    let getData = realm.objects(User.self).filter("firstDate > newDate")
    userData = getData
    print("userData", userData!)
}

When trying to retrieve the objects, the app crashes.. Is it something wrong with the filter format?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Anton Diablo
  • 23
  • 1
  • 5
  • Don't do force unwrapping on a value that can be `nil`. Are you sure the data actually contains some entries which the filter should return? – Dávid Pásztor Oct 06 '17 at 00:53
  • @DávidPásztor It should contain entries. I have opened the realm file in Realm Browser, and got this: https://image.ibb.co/fSoxdw/Screen_Shot_2017_10_06_at_03_02_58.png So as you can see, it should be just fine(?) Left is `firstDate` and right is `newDate`. – Anton Diablo Oct 06 '17 at 01:04
  • There are no entries for which `firstDate > newDate`, so `getData` is `nil` as expected... – Dávid Pásztor Oct 06 '17 at 01:06
  • You say that your app crashes... care to share any information at all about the crash?.. – bdash Oct 06 '17 at 01:07
  • @bdash Error message is only: `libc++abi.dylib: terminating with uncaught exception of type NSException`. – Anton Diablo Oct 06 '17 at 01:12
  • @DávidPásztor How do you suggest I do this then? To get all the object created after `firstData` date? – Anton Diablo Oct 06 '17 at 01:13
  • @AntonDiablo you should change the relation sign in your filter. Moreover, if `firstDate` will stay the same for all objects, you shouldn't persist it in Realm and definitely shouldn't store it in every single object. – Dávid Pásztor Oct 06 '17 at 01:23
  • @DávidPásztor Why shouldn't I store it in every single object? `firstDate` is only for the first objects added at first launch. Objects added later then first launch will not have `firstDate `. – Anton Diablo Oct 06 '17 at 01:30

1 Answers1

1

Try this:

var yourNSDate = NSDate()
let predicate = NSPredicate(format: "firstDate < %@", yourNSDate)
let dataResults = realm.objects(User.self).filter(predicate)
userData = dataResults

Replace that with the code below if (homeIndexPathRow == 0) { ...

Erik Auranaune
  • 1,384
  • 1
  • 12
  • 27