NSPredicate有多个陈述

时间:2013-04-13 07:45:15

标签: ios cocoa-touch core-data

我有NSPredicate个四个语句/参数。似乎所有这些都不是“包含”的。它看起来像这样:

predicate = [NSPredicate predicateWithFormat:@"user.youFollow = 1 || user.userId = %@ && user.youMuted = 0 && postId >= %d", [AppController sharedAppController].currentUser.userId, self.currentMinId.integerValue];

似乎最后一部分:&& postId >= %d被忽略了。如果我尝试:

predicate = [NSPredicate predicateWithFormat:@"user.youFollow = 1 || user.userId = %@ && user.youMuted = 0 && postId = 0", [AppController sharedAppController].currentUser.userId, self.currentMinId.integerValue];

我得到相同的结果(应为0)。我想知道这样的谓词应该如何看待?

2 个答案:

答案 0 :(得分:3)

您可以尝试使用代码吗?

NSPredicate *youFollowPred = [NSPredicate predicateWithFormat:@"user.youFollow == 1"];
NSPredicate *userIdPred = [NSPredicate predicateWithFormat:@"user.userId == %@",[AppController sharedAppController].currentUser.userId];
NSPredicate *youMutedPred = [NSPredicate predicateWithFormat:@"user.youMuted == 0"];
NSPredicate *postIdPred = [NSPredicate predicateWithFormat:@"postId >= %d", self.currentMinId.integerValue];

NSPredicate *orPred = [NSCompoundPredicate orPredicateWithSubpredicates:[NSArray arrayWithObjects:youFollowPred,userIdPred, nil]];

NSPredicate *andPred = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:youMutedPred,postIdPred, nil]];

NSPredicate *finalPred = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:orPred,andPred, nil]];

答案 1 :(得分:3)

正如在讨论中发现的那样,真正的问题是谓词被用于 获取的结果控制器,以及谓词中使用的变量随时间变化。

在这种情况下,您必须重新创建谓词和获取请求。这是记录在案的 在NSFetchedResultsController Class Reference

中的“修改抓取请求”

所以在你的情况下,如果self.currentMinId发生变化,你应该

// create a new predicate with the updated variables:
NSPredicate *predicate = [NSPredicate predicateWithFormat:...]
// create a new fetch request:
NSFetchRequest *fetchRequest = ...
[fetchRequest setPredicate:predicate];

// Delete the section cache if you use one (better don't use one!)
[self.fetchedResultsController deleteCacheWithName:...];

// Assign the new fetch request and re-fetch the data:
self.fetchedResultsController.fetchRequest = fetchRequest;
[self.fetchedResultsController performFetch:&error];

// Reload the table view:
[self.tableView reloadData];