NSPredicate NSManagedObject的字符串属性的长度 [英] NSPredicate for an NSManagedObject's string attribute's length

查看:159
本文介绍了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?

这是我一直在尝试的例子,我有一个感觉是letters.length表示法,我也尝试过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];

Joss。

这篇关于NSPredicate NSManagedObject的字符串属性的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆