Question

Could someone please help me define a predicate that returns only NSManagedObject's who's "letters" attribute length is within a certain range?

Here's the example I've been trying, I've got a feeling it's the letters.length notation, I've also tried the kvc letters.@length with no success.. What am I doing wrong?

NSManagedObjectContext *context = ...;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Word" inManagedObjectContext:context];
[fetchRequest setEntity:entity];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"letters" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"letters.length BETWEEN %@", [NSArray arrayWithObjects: [NSNumber numberWithInt:5], [NSNumber numberWithInt:20], nil]];
[fetchRequest setPredicate:predicate];

NSUInteger limit = 20;
[fetchRequest setFetchLimit:limit];

NSError *error = nil;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
Was it helpful?

Solution

Not sure how this code snippet is performance wise but here is my answer to your question:

NSString *attributeName = @"letters";
NSString *attributeValue = [NSString stringWithFormat:@"'.{%d,%d}'", 5, 20];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K MATCHES %@", attributeName, attributeValue];
[fetchRequest setPredicate:predicate];

Joss.

OTHER TIPS

I've got some bad news. You can't do this. There is no length attribute for strings in the NSPredicate (that I've been able to find).

What I would recommend you do is add an attribute for the length of the stored string in your managed object that gets set when you set the letters attribute. You can then do your query on that attribute and return the values you want.

In case someone is looking for a way to test whether a string has length using an NSPredicate, it is possible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top