Skip to content

Instantly share code, notes, and snippets.

@ddeville
Created October 22, 2013 16:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ddeville/7103822 to your computer and use it in GitHub Desktop.
Save ddeville/7103822 to your computer and use it in GitHub Desktop.
Think of a parent view controller that contains two children view controllers. The title of the parent view controller is a mixture of the titles of its children. The title of the second view controller depends on the name of its represented object too. Now, one would only need to bind the title of the window (for example) to the parent view con…
@interface ParentViewController : NSViewController
@property (strong, nonatomic) FirstChildViewController *firstViewController;
@property (strong, nonatomic) SecondChildViewController *secondViewController;
@end
@implementation ParentViewController
- (NSString *)title
{
NSString *firstTitle = [[self firstViewController] title];
NSString *secondTitle = [[self secondViewController] title];
return [[firstTitle stringByAppendingString:@" - "] stringByAppendingString:secondTitle];
}
+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key
{
NSMutableSet *keyPaths = [NSMutableSet setWithSet:[super keyPathsForValuesAffectingValueForKey:key]];
if ([key isEqualToString:@"title"]) {
[keyPaths addObject:[[@"firstViewController" stringByAppendingString:@"."] stringByAppendingString:@"title"]];
[keyPaths addObject:[[@"secondViewController" stringByAppendingString:@"."] stringByAppendingString:@"title"]];
}
return keyPaths;
}
@end
@interface FirstChildViewController : NSViewController
- (NSString *)title;
@end
@implementation FirstChildViewController
- (NSString *)title
{
return @"Home";
}
@end
@interface SecondChildViewController : NSViewController
@property (strong, nonatomic) id representedObject;
- (NSString *)title;
@end
@implementation SecondChildViewController
+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key
{
NSMutableSet *keyPaths = [NSMutableSet setWithSet:[super keyPathsForValuesAffectingValueForKey:key]];
if ([key isEqualToString:@"title"]) {
[keyPaths addObject:[[@"representedObject" stringByAppendingString:@"."] stringByAppendingString:@"name"]];
}
return keyPaths;
}
- (NSString *)title
{
return [representedObject name];
}
@end
@lukaskubanek
Copy link

@ddeville Why are you creating key paths using -stringByAppendingString: and not writing them directly in string literals?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment