1

我有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)。我想知道这样的谓词应该是什么样子?

4

2 回答 2

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]];
于 2013-04-13T10:10:13.940 回答
3

正如讨论中证明的那样,真正的问题是谓词用于获取结果控制器中,并且谓词中使用的变量会随着时间而变化。

在这种情况下,您必须重新创建谓词和获取请求。这在NSFetchedResultsController 类参考中的“修改获取请求”中有记录。

所以在你的情况下,如果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];
于 2013-04-13T12:38:45.110 回答