首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用NSPredicate的NSFetchRequest

使用NSPredicate的NSFetchRequest
EN

Stack Overflow用户
提问于 2014-12-28 02:27:40
回答 1查看 32关注 0票数 0

我正在尝试以这种方式通过核心数据数据库创建所有过滤搜索结果的NSArray:

代码语言:javascript
复制
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription *entity = [NSEntityDescription
                               entityForName:@"AllFiles" inManagedObjectContext:context];
[fetchRequest setEntity:entity];

NSPredicate *p1 = [NSPredicate predicateWithFormat:@"userID == %@", userID];
NSPredicate *p2 = [NSPredicate predicateWithFormat:@"folderNumber == %d", folderNumber];
NSPredicate *p3 = [NSPredicate predicateWithFormat:@"fileType == %@", type];

NSPredicate *fetchPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[p1, p2, p3]];
[fetchRequest setPredicate:fetchPredicate];

NSError *error;
NSArray* returnArray = [context executeFetchRequest:fetchRequest error:&error];

这些文件是这样创建的:

代码语言:javascript
复制
AllFiles *newFile = [NSEntityDescription
                                        insertNewObjectForEntityForName:@"AllFiles"
                                        inManagedObjectContext:context];
newFile.userID = userID;
newFile.folderNumber = [NSString stringWithFormat:@"%d", folderNumber];
....

正如您所看到的,我正在尝试过滤给定的一些参数的结果:

代码语言:javascript
复制
@"userID == %@", userID

但是,返回所有结果,而不进行过滤...你知道为什么吗?

EN

回答 1

Stack Overflow用户

发布于 2014-12-28 06:17:04

您正在使用OR谓词,这3个谓词中至少有一个与所有谓词匹配。我怀疑[NSPredicate predicateWithFormat:@"fileType == %@", type]在收集你所有的文件

试着像这样合成一个和...

代码语言:javascript
复制
NSPredicate *idPredicate = [NSPredicate predicateWithFormat:@"userID == %@", userID];
NSPredicate *folderNumPredicate = [NSPredicate predicateWithFormat:@"folderNumber == %d", folderNumber];
NSPredicate *typePredicate = [NSPredicate predicateWithFormat:@"fileType == %@", type];

NSPredicate *fetchPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[idPredicate, folderNumPredicate, typePredicate];

[fetchRequest setPredicate:fetchPredicate];

请记住,andPredicateWithSubpredicatesorPredicateWithSubpredicates会返回一个NSPredicate,因此如果需要,可以将它们以复杂的方式组合在一起。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27670231

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档