Created
March 4, 2020 06:24
-
-
Save SoundBlaster/44ec77c6d35199bb34adb6d60bf31247 to your computer and use it in GitHub Desktop.
SwitchableProxy to enable and disable methods of some T object by one property
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
/// SwitchableProxy.h content: | |
#import <Foundation/Foundation.h> | |
NS_ASSUME_NONNULL_BEGIN | |
@protocol SwitchableObject | |
@property (nonatomic, readwrite, assign, getter=isEnabled) BOOL enabled; | |
+ (BOOL)isSwitchableSelector:(SEL)selector; | |
@end | |
@interface SwitchableProxy <T, SwitchableObject> : NSObject | |
@property (nonatomic, readwrite, assign, getter=isEnabled) BOOL enabled; | |
- (instancetype)init NS_UNAVAILABLE; | |
+ (instancetype)new NS_UNAVAILABLE; | |
- (T)initWithObject:(T)object NS_DESIGNATED_INITIALIZER; | |
+ (T)proxy:(T)object; | |
@end | |
NS_ASSUME_NONNULL_END | |
/// SwitchableProxy.m content: | |
#import "SwitchableProxy.h" | |
@interface SwitchableProxy () { | |
NSObject *_object; | |
} | |
@end | |
@implementation SwitchableProxy | |
- (id)initWithObject:(id)object { | |
self = [super init]; | |
if (self != nil) { | |
_object = object; | |
_enabled = [object isEnabled]; | |
} | |
return self; | |
} | |
+ (id)proxy:(id)object { | |
return [[self alloc] initWithObject:object]; | |
} | |
- (void)setEnabled:(BOOL)enabled { | |
_enabled = enabled; | |
} | |
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { | |
if ([_object respondsToSelector:aSelector]) { | |
return [_object methodSignatureForSelector:aSelector]; | |
} | |
return nil; | |
} | |
- (void)forwardInvocation:(NSInvocation *)anInvocation { | |
if ([_object respondsToSelector:anInvocation.selector]) { | |
if ([self isEnabled] || ![_object.class isSwitchableSelector:anInvocation.selector]) { | |
[anInvocation invokeWithTarget:_object]; | |
} | |
} | |
} | |
- (BOOL)respondsToSelector:(SEL)aSelector { | |
return [_object respondsToSelector:aSelector]; | |
} | |
#pragma mark - Description | |
- (NSString *)description { | |
return [NSString stringWithFormat:@"%@ | %@ | enabled: %@", self.class, _object, self.enabled?@"YES":@"NO"]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment