Skip to content

Instantly share code, notes, and snippets.

@kyktommy
Created November 10, 2013 04:49
Show Gist options
  • Save kyktommy/7393967 to your computer and use it in GitHub Desktop.
Save kyktommy/7393967 to your computer and use it in GitHub Desktop.
KVO, Notification, delegate
// mainViewController
@interface MainViewController () <AwesomeViewController>
_awesomeViewController.delegate = self;
- (void)didSelectLabel;
// awesomeViewController
@protocol AwsomeViewControllerDelegate <NSObject>
@optional
- (void)didSelectLabel;
@end
- (void)action
{
if ([self.delegate respondsToSelector:@selector(didSelectLabel)]) {
[self.delegate didSelectLabel];
} else {
NSLog(@"no delegate didSelectLabel found");
}
}
// mainViewController.m
[_tableViewController addObserver:self
forKeyPath:@"arr"
options:NSKeyValueObservingOptionNew
context:NULL];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"%s", __func__);
if ([keyPath isEqualToString:@"arr"] && [object isEqual:_tableViewController]) {
NSLog(@"%@", change);
}
}
// tableViewController.m
[self willChangeValueForKey:@"arr"];
[self.arr addObject:@"watermelon"];
[self didChangeValueForKey:@"arr"];
// or
self.arr = [@[@"apple", @"pear"] mutableCopy];
// use notification center as a event bus
// mainViewController
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleNotification:)
name:@"addNewObject"
object:nil];
- (void)handleNotification: (NSNotification *) notification
{
NSLog(@"%@", notification);
}
// tableViewController
[[NSNotificationCenter defaultCenter] postNotificationName:@"addNewObject" object:self.arr];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment