2013-04-13 110 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)」,... '。 –