NSPredicate for NSManagedObject string attribute length

Can someone help me define a predicate that only NSManagedObject returns, the length of the “letter” attribute is within a certain range?

Here is an example that I tried, I have the feeling that it is the letter letter.length, I also tried the letters kvc. @ length without 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]; 
+4
nsstring core-data nsmanagedobject nspredicate
Sep 05 '10 at 1:20
source share
3 answers

I don’t know how this piece of code affects performance, 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.

+7
Jan 03 '13 at 23:00
source share

I have a bad news. You cannot do this. There is no length attribute for strings in NSPredicate (which I could find).

I would recommend that you add the length attribute of the stored string in the managed object, which is set when you set the letter attribute. Then you can fulfill your request for this attribute and return the desired values.

+4
Sep 05 2018-10-09T00:
source share

If someone is looking for a way to check if a length has a length using NSPredicate, .

+3
Feb 14 '12 at 17:11
source share



All Articles