Skip to content

Instantly share code, notes, and snippets.

@jamztang
Created January 21, 2016 14:26
Show Gist options
  • Save jamztang/87f26c04ef9afe8f6777 to your computer and use it in GitHub Desktop.
Save jamztang/87f26c04ef9afe8f6777 to your computer and use it in GitHub Desktop.
Generic HOM for NSArray
#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
#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