2013-01-02 45 views
6

現在我正面臨NSPredicate中的單引號(')問題。NSPredicate單引號問題

這裏是我的查詢:

NSPredicate *query = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"s_name='%@' AND s_regno=%d",Name,[RegNo intValue]]]; 

當我與名稱進行篩選,「約翰」,它是確定和完全沒有錯誤。但我使用這個名字,「瑪麗'Monny」。有一個錯誤。

我懷疑這是因爲單引號。請幫我解決這個問題。

感謝

回答

1

如果name = @「貝爾」,你可以嘗試讓謂詞是這樣的:

NSPredicate *query = [NSPredicate predicateWithFormat:@"name == \"%@\"", name]; 

就用雙引號代替標準的單引號。

+3

如果你的輸入字符串有雙引號,那麼是什麼? – northernman

12

作爲速戰速決,你不應該需要在所有的NSString部分。這個替換是predicateWithFormat:方法的全部要點!簡單地使用:

NSPredicate *query = [NSPredicate predicateWithFormat:@"s_name == %@ AND s_regno == %d", Name, [RegNo intValue]]; 

我喜歡避免完全格式化字符串,而是在代碼中構建謂詞。

NSPredicate *nameQuery = 
[NSComparisonPredicate predicateWithLeftExpression:[NSExpression expressionForKeyPath:@"s_name"] 
            rightExpression:[NSExpression expressionForConstantValue:Name] 
              modifier:NSDirectPredicateModifier 
               type:NSLikePredicateOperatorType 
              options:NSCaseInsensitivePredicateOption|NSDiacriticInsensitivePredicateOption]; 

NSPredicate *regNoQuery = 
[NSComparisonPredicate predicateWithLeftExpression:[NSExpression expressionForKeyPath:@"s_regno"] 
            rightExpression:[NSExpression expressionForConstantValue:RegNo] 
              modifier:NSDirectPredicateModifier 
               type:NSEqualToPredicateOperatorType 
              options:0]; 

NSPredicate *query = [NSCompoundPredicate andPredicateWithSubpredicates:@[nameQuery,regNoQuery]]; 

請注意,我說NSCaseInsensitivePredicateOption|NSDiacriticInsensitivePredicateOption做對名稱進行區分和變音符號,大小寫的比較,如s_name like[cd] %@。如果你不需要,你當然可以使用type:NSEqualToPredicateOperatorTypeoptions:0

+0

你的「快速修復」是正確的答案。 –

+0

這應該被標記爲正確的答案。 – northernman