我有一个NSArray并且需要过滤掉任何null的字符串,或者更确切地说,有''(空字符串).我怎么做?我试过做:
NSPredicate *predicateName = [NSPredicate predicateWithFormat:@"(name!=nil)"];
Run Code Online (Sandbox Code Playgroud)
但这似乎不起作用.或许它确实如此,但有不同种类的空...
我一直在我的项目中使用核心数据.几天前,我发现保存在数据库中的一些记录没有显示在应用程序UI中.我已经跟踪了它,发现当我使用NSPredicate过滤掉空字符串时,它们根本没有被取出.所有这些都以非字母字符开头.
为了澄清这个问题,我创建了一个示例项目并将一些示例数据添加到数据库中.假设它们是"Sample","+ sample","Sample +".
这是我用来过滤掉空字符串的代码片段."text"是字符串属性的名称,而moc是NSManagedObjectContext实例.
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"BasicEntity"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"text.length > 0"];
[request setPredicate:predicate];
NSArray *samples = [moc executeFetchRequest:request error:&error];
Run Code Online (Sandbox Code Playgroud)
结果数组只包含2个实体,即"Sample"和"Sample +".
我甚至在包含上面示例字符串的简单数组上尝试了相同的谓词(当然,使用self.length而不是text.length),并且我正确地得到了所有3个.
我想知道是否有人遇到同样的问题.或者我在使用核心数据时遗漏了什么?在iOS 7.0.3模拟器和7.0.6 iPad Air上测试.
更新:正如在另一个线程中所回答的,我使用正则表达式解决了这个问题.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"text MATCHES %@", @".{1,}"];
Run Code Online (Sandbox Code Playgroud)
不过,我相信我使用的原始谓词是有效的.我将向Apple提交一个错误以获取他们的意见.
假如我有一个实体Fragment,它有一个属性'text'是一个字符串,我想查询Fragment其text长度为5 的列表:
[NSPredicate predicateWithFormat:@"position == %@ AND text.length == %d", pos, 5];
Run Code Online (Sandbox Code Playgroud)
它不起作用(即返回没有结果),但如果我在查询中删除text.length它可以工作,我确定有长度为5的文本,那么我需要将它更改为什么?
谢谢!
有人可以帮我定义一个谓词,只返回NSManagedObject的"字母"属性长度在一定范围内吗?
这是我一直在尝试的例子,我感觉这是字母.长度表示法,我也尝试过kvc字母.@长度没有成功..我做错了什么?
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];
Run Code Online (Sandbox Code Playgroud)