本文介绍了NSPredicate 用于 NSManagedObject 的字符串属性的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以帮我定义一个谓词,它只返回 NSManagedObject 的字母"属性长度在一定范围内吗?
Could someone please help me define a predicate that returns only NSManagedObject's who's "letters" attribute length is within a certain range?
这是我一直在尝试的示例,我有一种感觉是字母长度表示法,我也尝试了 kvc 字母.@length 没有成功..我做错了什么?
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];
推荐答案
不确定此代码片段在性能方面的表现如何,但这是我对您问题的回答:
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];
乔斯.
这篇关于NSPredicate 用于 NSManagedObject 的字符串属性的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!