Skip to content

Instantly share code, notes, and snippets.

@jdewind
Last active January 4, 2016 17:19
Show Gist options
  • Save jdewind/8653305 to your computer and use it in GitHub Desktop.
Save jdewind/8653305 to your computer and use it in GitHub Desktop.
ReactiveCocoaDelegateExample
- (void)viewDidLoad {
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame: CGRectZero];
self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
self.searchController.delegate = self;
// Place it in view
searchBar.delegate = self;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
self.searchResults = [self search: text];
}
- (void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)searchController {
self.isSearching = YES;
}
- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)searchController {
self.isSearching = NO;
}
- (void)viewDidLoad {
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame: CGRectZero];
self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
RAC(self, searchResults) = [self rac_liftSelector:@selector(search:) withSignals:self.searchBar.rac_textSignal, nil];
RAC(self, searching) = [[self.searchController rac_isActiveSignal] doNext:^(id x) {
NSLog(@"Searching %@", x);
}];
}
@implementation UISearchBar (RAC)
- (RACSignal *)rac_textSignal {
self.delegate = self;
RACSignal *signal = objc_getAssociatedObject(self, _cmd);
if (signal != nil) return signal;
/* Create signal from selector */
signal = [[self rac_signalForSelector:@selector(searchBar:textDidChange:)
fromProtocol:@protocol(UISearchBarDelegate)] map:^id(RACTuple *tuple) {
return tuple.second;
}];
objc_setAssociatedObject(self, _cmd, signal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
return signal;
}
@end
@implementation UISearchDisplayController (RAC)
- (RACSignal *)rac_isActiveSignal {
self.delegate = self;
RACSignal *signal = objc_getAssociatedObject(self, _cmd);
if (signal != nil) return signal;
/* Create two signals and merge them */
RACSignal *didBeginEditing = [[self rac_signalForSelector:@selector(searchDisplayControllerDidBeginSearch:)
fromProtocol:@protocol(UISearchDisplayDelegate)] mapReplace:@YES];
RACSignal *didEndEditing = [[self rac_signalForSelector:@selector(searchDisplayControllerDidEndSearch:)
fromProtocol:@protocol(UISearchDisplayDelegate)] mapReplace:@NO];
signal = [RACSignal merge:@[didBeginEditing, didEndEditing]];
objc_setAssociatedObject(self, _cmd, signal, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
return signal;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment