开发者

Custom NSPredicate in Cocoa

I have an NSTableView whose columns are bound to a subclass of NSArrayController. Each entry of the 'value' column is a list of file paths (in the model), in particular, PATH and PYT开发者_如何学JAVAHONPATH for an app.

What I want is to control edits to these values to as they are made, to ensure that each of the paths on the list is a valid one. Since I'm using bindings, I'm thinking I should write some kind of NSPredicate but I'd like to have it use a function that I define to do the filter, since the testing is a bit complex. How do you use a custom function with an NSPredicate?

Or should I consider another approach?

Thanks.

UPDATE:

I have figured out how to make the string containing filepaths into an expression that evaluates to what I want, using a category on NSString that adds the method validate. But I still don't know how to get it into a filter predicate.

NSString *s = @"~:~/Desktop";
NSExpression *f = [NSExpression expressionForConstantValue:s];
NSExpression *e = [NSExpression expressionForFunction:f
                                         selectorName:@"validate" 
                                            arguments:nil];

I guess this would basically be a filter predicate that always spits out what the expression evaluates to..


Pretty simple:

NSString *s = @"~:~/Desktop";
NSPredicate *p = [NSPredicate predicateWithFormat:@"FUNCTION(%@, 'validate') == YES", s];

Or if you have an array of strings that you want to filter to find all the ones that pass validation:

NSArray *array = ...; //your array of strings needing validation
NSPredicate *p = [NSPredicate predicateWithFormat:@"FUNCTION(SELF, 'validate') == YES"];
NSArray *filtered = [array filteredArrayUsingPredicate:p];

One thing to note here is that the result of the -validate method MUST be an id. So if it returns a true/false value, it should return a BOOL boxed in an NSNumber. (The YES in the predicate format string is automatically converted into an NSNumber for you)

Once you've got the predicate, you can set it into your array controller or whatever.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜