Skip to content

Instantly share code, notes, and snippets.

@wjlafrance
Created February 16, 2013 19:39
Show Gist options
  • Save wjlafrance/4968392 to your computer and use it in GitHub Desktop.
Save wjlafrance/4968392 to your computer and use it in GitHub Desktop.
A simple NSPredicate such as "username == wjl" can be parsed as a key-value pair.
//
// NSPredicate+KeyValue.h
// IncrementalAppnet
//
// Created by William LaFrance on 2/16/13.
//
#import <Foundation/Foundation.h>
@interface NSPredicate (KeyValue)
- (BOOL)isSimpleKeyValue;
- (NSString *)key;
- (NSString *)value;
@end
//
// NSPredicate+KeyValue.m
// IncrementalAppnet
//
// Created by William LaFrance on 2/16/13.
//
#import "NSPredicate+KeyValue.h"
@implementation NSPredicate (KeyValue)
- (BOOL)isSimpleKeyValue
{
NSRegularExpression *simpleKeyValueExpression =
[NSRegularExpression regularExpressionWithPattern:@"^[A-Za-z0-9]+ == [A-Za-z0-9]+$"
options:0
error:nil];
assert(simpleKeyValueExpression != nil);
NSTextCheckingResult *match = [simpleKeyValueExpression firstMatchInString:self.description
options:0
range:NSMakeRange(0, self.description.length)];
if (match.range.location == 0 && match.range.length == 0) {
return NO;
} else {
return YES;
}
}
- (NSString *)key
{
NSArray *components = [self.description componentsSeparatedByString:@" == "];
return components[0];
}
- (NSString *)value
{
NSArray *components = [self.description componentsSeparatedByString:@" == "];
return components[1];
}
@end
//
// NSPredicateKeyValueTests.h
// IncrementalAppnet
//
// Created by William LaFrance on 2/16/13.
//
#import <SenTestingKit/SenTestingKit.h>
@interface NSPredicateKeyValueTests : SenTestCase
@end
//
// NSPredicateKeyValueTests.m
// IncrementalAppnet
//
// Created by William LaFrance on 2/16/13.
//
#import "NSPredicateKeyValueTests.h"
#import "NSPredicate+KeyValue.h"
@implementation NSPredicateKeyValueTests
- (void)testIsSimpleKeyValue
{
NSPredicate *p1 = [NSPredicate predicateWithFormat:@"fizz == buzz"];
NSPredicate *p2 = [NSPredicate predicateWithFormat:@"fizz == buzz && foobar == bazquux"];
STAssertTrue(p1.isSimpleKeyValue, nil);
STAssertFalse(p2.isSimpleKeyValue, nil);
}
- (void)testKey
{
NSPredicate *p1 = [NSPredicate predicateWithFormat:@"fizz == buzz"];
NSPredicate *p2 = [NSPredicate predicateWithFormat:@"foo == bar"];
STAssertEqualObjects(p1.key, @"fizz", nil);
STAssertEqualObjects(p2.key, @"foo", nil);
}
- (void)testValue
{
NSPredicate *p1 = [NSPredicate predicateWithFormat:@"fizz == buzz"];
NSPredicate *p2 = [NSPredicate predicateWithFormat:@"foo == bar"];
STAssertEqualObjects(p1.value, @"buzz", nil);
STAssertEqualObjects(p2.value, @"bar", nil);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment