简单的 NSPredicate @"1 == 0" 不过滤获取的结果?

Posted

技术标签:

【中文标题】简单的 NSPredicate @"1 == 0" 不过滤获取的结果?【英文标题】:Simple NSPredicate @"1 == 0" not filtering fetched results? 【发布时间】:2012-09-01 09:45:20 【问题描述】:

这段代码有什么问题?

我知道这是一个愚蠢的谓词。但这只是为了表明,如果这有效,应该过滤掉所有内容,对吧?

不知何故,它不是。我在我的数据库中获取了每个 Month 对象,而我应该什么都没有。

我想这告诉我问题可能不在谓词中?

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Month" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];

[fetchRequest setPredicate: [NSPredicate predicateWithFormat:@"1 == 0"]];

NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"month_" ascending:YES];

    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor1, nil];
    [fetchRequest setSortDescriptors:sortDescriptors];
[fetchRequest setFetchBatchSize:20];

NSFetchedResultsController *theFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                    managedObjectContext:managedObjectContext
                                      sectionNameKeyPath:@"month_"
                                               cacheName:@"Root"];



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

    return [[_fetchedResultsController sections] count];

我真正想做的是,

[NSPredicate predicateWithFormat:@"year.year_ == %d", year]

我也试过这个,

[NSPredicate predicateWithFormat:@"month_ == %d", 1]

只是看看它是否有效。但什么都没有。

编辑:

此时,无论我设置什么谓词,只要它是有效的、格式良好的谓词即可。它不抱怨,并得到我所有的对象。它只是没有过滤任何东西。

我几乎使用 Apple 文档中的样板代码。

谁能帮我解决这个问题?

谢谢!

【问题讨论】:

因为1 == 0 始终为假,您将没有符合此条件的结果。 这正是我的问题。无论我设置什么谓词,它都会返回所有内容。 1 == 0,应该不会给我任何结果。但不知何故,它让我得到了所有的对象。 尝试删除缓存。另外,如果您已经切换到 ios6,那么现在NSFetchedResultsController 中存在一些与谓词和限制有关的错误。 太棒了!非常感谢@Kyr 删除缓存做到了! =) @KyrDunenkoff 我很快就会切换到 iOS 6..你有任何链接可以找到更多关于 NSFetchedResultsController 错误的链接,以便我做好准备吗? 【参考方案1】:

如果使用缓存,那么 fetchRequest 的缓存应该在被重用之前被删除。

调用 deleteCacheWithName: 解决了问题。

【讨论】:

以上是关于简单的 NSPredicate @"1 == 0" 不过滤获取的结果?的主要内容,如果未能解决你的问题,请参考以下文章

使用 Coredata 和 NSFetchRequest 进行“IN”搜索时如何格式化 NSPredicate

如何向 NSPredicate 添加连接

NSPredicate 用于评估字符串

NSPredicate 用数组搜索逗号分隔值

带有 NSPredicate "SELF IN %@" 的 NSFetchedResultsController 仅在应用重新启动后有效

iOS谓词NSPredicate的简单使用