0

I've just discovered Realm and started working with it in objective-c.

I'm trying to get the objects where create_date before specific date and time

I read this answer on StackOverflow, So i tried this :

NSString *dateString = @"2015-06-03 08:24:00";
NSDateFormatter * dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *newDate = [dateFormatter dateFromString:dateString];

RLMRealm *realm = [RLMRealm defaultRealm];
NSString *_where = [NSString stringWithFormat:@"create_date < '%@'", newDate];
RLMResults *results = [database_articles objectsInRealm:realm where:_where];

but i'm getting the following error:

'Expected object of type date for property 'created' on object of type 'database_articles', but received: 2015-06-03 05:24:00 +0000'

So how can I pass NSDATE in a query in Realm ??

Thanks in advance ..

Community
  • 1
  • 1
MujtabaFR
  • 5,956
  • 6
  • 40
  • 66

1 Answers1

4

You used the method + (RLMResults *)objectsInRealm:(RLMRealm *) where:(NSString *), ...;, which is a convenience API, taking a string and further arguments and constructing a NSPredicate from it on-the-fly for you. By providing your arguments first to [NSString stringWithFormat:], you serialize your date, so that it comes to this error.

Use one of those two variants to avoid that:

RLMResults *results = [database_articles objectsInRealm:realm where:@"create_date < %@", newDate];

NSPredicate *_where = [NSPredicate predicateWithFormat:@"create_date < %@", newDate];
RLMResults *results = [database_articles objectsInRealm:realm withPredicate:_where];
marius
  • 7,766
  • 18
  • 30
  • but i should be like this `NSPredicate *_where = [NSPredicate predicateWithFormat:@"created < %@", newDate];` `RLMResults *results = [database_articles objectsInRealm:realm withPredicate:_where];` – MujtabaFR Jul 30 '15 at 10:06
  • Also you need to remove the **Quotation Marks** around **%@** – MujtabaFR Jul 31 '15 at 16:41