2013-04-13 113 views
1

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

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)。我不知道这样的谓词应该看起来如何?

+0

你有没有试着用括号?只是为了看看它是否是一个优先问题... – Francesco

+0

我试过了:'(user.youFollow = 1 || user.userId =%@)&&(user.youMuted = 0 && postId> =%d)'。 – Anders

+0

'NSLog(@“%@”,[predicate description]);'print? –

回答

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]; 
+0

谢谢,让它工作!小记,setFetchRequest是只读的。我做了:'self.fetchedResultsController.fetchRequest setPredicate ...'。 – Anders

+0

@Anders:感谢您的反馈! 'self.fetchedResultsController.fetchRequest setPredicate:newPredicate]'也可能工作,也许你想尝试。在这种情况下,您只需要一个新的谓词,而不是新的获取请求。 –

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]]; 
+0

谢谢,它的工作原理。你知道是否 - 'NSPredicate * postIdPred = [NSPredicate predicateWithFormat:@“postId> =%d”,self.currentMinId.integerValue]; - 可以有一个动态的'%d'变量。在进行新的抓取之前,需要更新我的谓词。 – Anders

+1

@sunilz:请注意,您的代码完全等同于谓词'“(user.youFollow = 1 || user.userId =%@)&&(user.youMuted = 0 && postId> =%d)”,... '。 –