Last active
August 29, 2015 14:18
-
-
Save chrisladd/c2e5bd2b094900ea2df2 to your computer and use it in GitHub Desktop.
A picky array to satisfy Loyal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// LYLPickyArray.h | |
// | |
// Copyright (c) 2015 NYTimes. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
@interface LYLPickyArray : NSMutableArray | |
- (instancetype)initWithClass:(Class)requiredClass predicate:(NSPredicate *)predicate; | |
@end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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