UIBarButtonItem+RACCommandSupport.m 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. //
  2. // UIBarButtonItem+RACCommandSupport.m
  3. // ReactiveCocoa
  4. //
  5. // Created by Kyle LeNeau on 3/27/13.
  6. // Copyright (c) 2013 GitHub, Inc. All rights reserved.
  7. //
  8. #import "UIBarButtonItem+RACCommandSupport.h"
  9. #import <ReactiveCocoa/EXTKeyPathCoding.h>
  10. #import "RACCommand.h"
  11. #import "RACDisposable.h"
  12. #import "RACSignal+Operations.h"
  13. #import <objc/runtime.h>
  14. static void *UIControlRACCommandKey = &UIControlRACCommandKey;
  15. static void *UIControlEnabledDisposableKey = &UIControlEnabledDisposableKey;
  16. @implementation UIBarButtonItem (RACCommandSupport)
  17. - (RACCommand *)rac_command {
  18. return objc_getAssociatedObject(self, UIControlRACCommandKey);
  19. }
  20. - (void)setRac_command:(RACCommand *)command {
  21. objc_setAssociatedObject(self, UIControlRACCommandKey, command, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  22. // Check for stored signal in order to remove it and add a new one
  23. RACDisposable *disposable = objc_getAssociatedObject(self, UIControlEnabledDisposableKey);
  24. [disposable dispose];
  25. if (command == nil) return;
  26. disposable = [command.enabled setKeyPath:@keypath(self.enabled) onObject:self];
  27. objc_setAssociatedObject(self, UIControlEnabledDisposableKey, disposable, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  28. [self rac_hijackActionAndTargetIfNeeded];
  29. }
  30. - (void)rac_hijackActionAndTargetIfNeeded {
  31. SEL hijackSelector = @selector(rac_commandPerformAction:);
  32. if (self.target == self && self.action == hijackSelector) return;
  33. if (self.target != nil) NSLog(@"WARNING: UIBarButtonItem.rac_command hijacks the control's existing target and action.");
  34. self.target = self;
  35. self.action = hijackSelector;
  36. }
  37. - (void)rac_commandPerformAction:(id)sender {
  38. [self.rac_command execute:sender];
  39. }
  40. @end