Skip to content

Instantly share code, notes, and snippets.

@chrisladd
Last active August 29, 2015 14:18
Show Gist options
  • Save chrisladd/c2e5bd2b094900ea2df2 to your computer and use it in GitHub Desktop.
Save chrisladd/c2e5bd2b094900ea2df2 to your computer and use it in GitHub Desktop.
A picky array to satisfy Loyal
//
// LYLPickyArray.h
//
// Copyright (c) 2015 NYTimes. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface LYLPickyArray : NSMutableArray
- (instancetype)initWithClass:(Class)requiredClass predicate:(NSPredicate *)predicate;
@end
//
// LYLPickyArray.m
//
// Copyright (c) 2015 NYTimes. All rights reserved.
//
#import "LYLPickyArray.h"
@interface LYLPickyArray() {
Class _requiredClass;
NSPredicate *_predicate;
}
@end
@implementation LYLPickyArray
- (instancetype)initWithClass:(Class)requiredClass predicate:(NSPredicate *)predicate {
self = [super init];
if (self) {
if (requiredClass) {
NSPredicate *classPredicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
return [evaluatedObject isKindOfClass:requiredClass];
}];
if (predicate) {
_predicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[classPredicate, predicate]];
}
else {
_predicate = classPredicate;
}
}
else if (predicate) {
_predicate = predicate;
}
else {
_predicate = [NSPredicate predicateWithValue:YES];
}
}
return self;
}
- (void)addObject:(id)anObject {
if ([_predicate evaluateWithObject:anObject]) {
[super addObject:anObject];
}
else {
NSAssert(NO, @"Invalid object type");
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment