Created
January 21, 2016 14:26
-
-
Save jamztang/87f26c04ef9afe8f6777 to your computer and use it in GitHub Desktop.
Generic HOM for NSArray
This file contains 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
#import <Foundation/Foundation.h> | |
@interface Each <Object> : NSObject | |
@property (nonatomic, strong) NSArray <Object> *array; | |
- (instancetype)initWithArray:(NSArray <Object> *)array; | |
@end | |
@interface NSArray <Object> (Each) | |
@property (nonatomic, readonly) Object each; | |
@end |
This file contains 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
#import "Each.h" | |
@implementation Each | |
- (instancetype)initWithArray:(NSArray *)array { | |
self = [super init]; | |
self.array = array; | |
return self; | |
} | |
- (void)forwardInvocation:(NSInvocation *)invocation { | |
[_array enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { | |
if ([obj respondsToSelector:[invocation selector]]) { | |
[invocation invokeWithTarget:obj]; | |
} | |
}]; | |
} | |
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { | |
__block NSMethodSignature *sign; | |
[_array enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { | |
if ([obj respondsToSelector:aSelector]) { | |
sign = [obj methodSignatureForSelector:aSelector]; | |
*stop = YES; | |
} | |
}]; | |
return sign; | |
} | |
@end | |
@implementation NSArray (Each) | |
- (id)each { | |
Each *each = [[Each alloc] initWithArray:self]; | |
return each; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment