Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Realm throw an exception when querying for `size == 4`?

My subclasses of RLMObject look like so:

@interface ImageRealm : RLMObject

@property NSString *httpsURL;
@property NSNumber<RLMInt> *size;

@end

RLM_ARRAY_TYPE(ImageRealm)

@interface PhotoRealm : RLMObject

@property NSNumber<RLMInt> *photoID;
@property RLMArray<ImageRealm *><ImageRealm> *differentSizeImages;  

- (id)initWithMantleModel:(PhotoModel *)photoModel;

@end

I want to filter PhotoRealm's differentSizeImages array to retrieve a specific ImageRealm. I tried with the following code:

PhotoRealm *photo = self.array[indexPath.row];
NSString *filter = @"size == 4";
ImageRealm *pecificImage = [[photo.differentSizeImages objectsWhere:filter] firstObject];

Where self.array is was initialized like this:

self.array = [PhotoRealm allObjects];

The code throws an exception:

2017-03-24 03:33:36.891 project_name[46277:3636358] *** Terminating app due to uncaught exception 'Invalid predicate expressions', reason: 'Predicate expressions must compare a keypath and another keypath or a constant value'


Update: Before I added the size property I was able to do the following (since I only had one image size):

ImageRealm *image = [photo.differentSizeImages objectAtIndex:0];

But now that I've added the size property I need to filter the array to select the correct size image.

See the following images for an idea of the data in my Realm file:

Photo

[differentSizeImgae[2]


And, I noticed the example queries in Realm's official documentation:

// Query using a predicate string
RLMResults<Dog *> *tanDogs = [Dog objectsWhere:@"color = 'tan' AND name BEGINSWITH 'B'"];

// Query using an NSPredicate
NSPredicate *pred = [NSPredicate predicateWithFormat:@"color = %@ AND name BEGINSWITH %@",
                                                     @"tan", @"B"];
tanDogs = [Dog objectsWithPredicate:pred];

These look the same as what I'm doing, so why am I seeing an exception?

like image 763
0xxxD Avatar asked Dec 10 '22 12:12

0xxxD


1 Answers

When attempting to use the predicate format string size == 4, you're seeing an exception like so:

Terminating app due to uncaught exception 'Invalid predicate expressions', reason: 'Predicate expressions must compare a keypath and another keypath or a constant value'

The reason for this is that size is a reserved word in NSPredicate's format syntax. You can escape reserved words by prefixing them with the # character, so your query would become #size == 4

like image 61
bdash Avatar answered Dec 29 '22 00:12

bdash