2014-06-05 41 views
0

當我代替字段名,我得到如下問題NSPredicate替代鍵將輸出

代碼

NSString *fieldName = @"name"; 
NSPredicate *template = [NSPredicate predicateWithFormat:@"$key = nil"]; 
NSPredicate *pred = [template predicateWithSubstitutionVariables:@{@"key": fieldName}]; 
NSLog(@"%@", pred); 

輸出繼電器

"name" = nil 

預計

name = nil 

問題

名稱有引號


怎樣才能不帶引號關鍵謂詞?

回答

1

你有一個關鍵路徑表達式,而不是一個字符串替換:

NSString *fieldName = @"name"; 
NSPredicate *template = [NSPredicate predicateWithFormat:@"$key = nil"]; 
NSExpression *keyPathExpr = [NSExpression expressionForKeyPath:fieldName]; 
NSPredicate *pred = [template predicateWithSubstitutionVariables:@{@"key": keyPathExpr}]; 
NSLog(@"%@", pred); 
// name == nil 
+0

謝謝,它的工作原理。 –

+0

[NSPredicate predicateWithFormat:@「%K = nil」,fieldName]也可能有效。 –