Skip to content

Instantly share code, notes, and snippets.

@aglee
Created October 6, 2011 14:51
Show Gist options
  • Save aglee/1267594 to your computer and use it in GitHub Desktop.
Save aglee/1267594 to your computer and use it in GitHub Desktop.
UNTESTED but I already know this is still not quite right. See http://www.mikeash.com/pyblog/key-value-observing-done-right.html for what could go wrong. Should use MAKVONotificationCenter to do the KVO. In any case, this code is just to give a general id
// MyViewTickler.h
#import <Cocoa/Cocoa.h>
@interface MyViewTickler : NSObject
{
}
+ (id)sharedInstance;
/*! Call this in your view's init methods (init with and without coder). */
- (void)startObservingView:(NSView *)aView;
/*! Call this in your view's dealloc method. */
- (void)stopObservingView:(NSView *)aView;
@end
@interface NSView (ViewTickler)
/*!
* Returns key paths that should trigger setNeedsDisplay:YES. Default returns
* empty array, so you can safely call super in any NSView class.
*/
+ (NSArray *)keyPathsRequiringRedisplay;
@end
//----------------------------------------------
// MyViewTickler.m
#import "MyViewTickler.h"
@implementation MyViewTickler
+ (id)sharedInstance
{
static MyViewTickler *s_sharedInstance = nil;
if (s_sharedInstance == nil)
{
s_sharedInstance = [[self alloc] init];
}
return s_sharedInstance;
}
- (void)startObservingView:(NSView *)aView
{
for (NSString *keyPath in [[aView class] keyPathsRequiringRedisplay])
{
[aView addObserver:self
forKeyPath:keyPath
options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
context:NULL];
}
}
- (void)stopObservingView:(NSView *)aView
{
for (NSString *keyPath in [[aView class] keyPathsRequiringRedisplay])
{
[aView removeObserver:self forKeyPath:keyPath];
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if ([object isKindOfClass:[NSView class]]
&& [[[object class] keyPathsRequiringRedisplay] containsObject:keyPath])
{
[(NSView *)object setNeedsDisplay:YES];
}
else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
@end
@implementation NSView (ViewTickler)
+ (NSArray *)keyPathsRequiringRedisplay
{
return [NSArray array];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment