Skip to content

Commit 08410f2

Browse files
committed
Added new category on NSPredicate.
1 parent ba147b3 commit 08410f2

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

NSPredicate+SSYPreflight.h

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
#import <Foundation/Foundation.h>
2+
3+
/*!
4+
@brief Returns whether or not the receiver can be used without raising
5+
an exception
6+
7+
@details If the user sets a row in NSPredicateEditor to the "matches"
8+
predicate type and fills in an invalid regular expression pattern such as this
9+
one:
10+
(*(
11+
the predicate returned by -[NSPredicateRuleEditor objectValue] be an invalid
12+
and an exception will be raised if such a predicate is passed to, for example,
13+
-[NSArrayController setFilterPredicate:], an exception will be raised :(
14+
15+
This method preflights such a predicate so you can avoid such an exception. */
16+
@interface NSPredicate (SSYValidate)
17+
18+
- (BOOL)preflightValidate ;
19+
20+
@end

NSPredicate+SSYPreflight.m

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#import "NSPredicate+SSYPreflight.h"
2+
3+
@implementation NSPredicate (SSYValidate)
4+
5+
- (BOOL)preflightValidate {
6+
BOOL answer = YES ;
7+
if ([self isKindOfClass:[NSComparisonPredicate class]]) {
8+
if ([(NSComparisonPredicate*)self predicateOperatorType] == NSMatchesPredicateOperatorType) {
9+
NSExpression* expression = [(NSComparisonPredicate*)self rightExpression] ;
10+
if ([expression expressionType] == NSConstantValueExpressionType) {
11+
id constantValue = [expression constantValue] ;
12+
if ([constantValue isKindOfClass:[NSString class]]) {
13+
NSError* error = nil ;
14+
NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:constantValue
15+
options:0
16+
error:&error] ;
17+
/* The error returned does not usually give much
18+
additional information. Here is an example:
19+
Error Domain=NSCocoaErrorDomain Code=2048 "The value “(*(” is invalid." UserInfo={NSInvalidValue=(*(}
20+
So, we don't bother passing it up. */
21+
if (!regex || (error != nil)) {
22+
answer = NO ;
23+
}
24+
[regex release] ;
25+
}
26+
}
27+
}
28+
}
29+
else if ([self respondsToSelector:@selector(subpredicates)]) {
30+
for (NSPredicate* predicate in [(NSCompoundPredicate*)self subpredicates]) {
31+
if (![predicate preflightValidate]) {
32+
answer = NO ;
33+
break ;
34+
}
35+
}
36+
}
37+
else {
38+
/*SSYDBL*/ NSLog(@"Whoooops: %@", [self className]) ;
39+
/* Could be something like NSTruePredicate */
40+
}
41+
42+
return answer ;
43+
}
44+
45+
@end

0 commit comments

Comments
 (0)