领域查询 'where before date'

Realm query 'where before date'

我刚刚发现 Realm 并开始在 objective-c.

中使用它

我正在尝试获取对象 where create_date before specific date and time

我读了 this answer on Whosebug,所以我尝试了这个:

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];

但我收到以下错误:

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

那么如何在 Realm 中的 query 中传递 NSDATE ??

提前致谢..

您使用了方法 + (RLMResults *)objectsInRealm:(RLMRealm *) where:(NSString *), ...;,这是一个方便的方法 API,获取一个字符串和进一步的参数并从中即时为您构建一个 NSPredicate。通过首先向 [NSString stringWithFormat:] 提供参数,您序列化了日期,因此出现了这个错误。

使用这两种变体之一来避免这种情况:

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];