Key-Path for an element of a dictionary property of an object in a predicate?
In short, I am looking for the correct predicate format to index into a dictionary attribute on an object.
I have an array of myObject instances, each with an attribute CPDictionary(NSMutableDictionary) extAttributes and I am trying to allow filtering based on values in extAttributes. I am defining my predicate as follows
[CPPredicate predicateWithFormat:@"extAttributes[%K] like[c] %@",key,val]
I am not sure what the correct key-path would be for this. Reading the documentation on NSPredicate it would seem that "extAttributes[%k]" might be an index into an array, not a dictionary. I have tried several alternatives and this is the only one that doesn't error. When inspecting the 开发者_StackOverflow社区resulting objects, the expressions in the predicate object appear to be correct. However, it doesn't have the intended result.
It looks like you might be confusing array and dictionary references. Just use a key path (dot-separated element names) to refer to nested elements or object properties, conceptually something like this:
[CPPredicate predicateWithFormat:@"%K like[c] %@", @"extAttributes.myNestedElementName", val];
Then again, I'm not all that familiar with Cappuccino, so I'm not sure if they've done something slightly different here, but this is the way it works in Cocoa and Cocoa touch.
EDIT
To compute the key dynamically, all you need to do is compose a key path string:
var keyPath = [CPString stringWithFormat:@"%@.%@", @"extAttributes", key];
You can now create the predicate as follows:
[CPPredicate predicateWithFormat:@"%K like[c] %@", keyPath, val];
EDIT
The equivalent code in Cocoa/Cocoa touch would be:
NSString *keyPath = [NSString stringWithFormat:@"%@.%@", @"extAttributes", key];
[NSPredicate predicateWithFormat:@"%K like[c] %@", keyPath, val];
精彩评论