Skip to content

Instantly share code, notes, and snippets.

@oks
Created March 12, 2016 14:20
Show Gist options
  • Save oks/570a32eded3733457a3b to your computer and use it in GitHub Desktop.
Save oks/570a32eded3733457a3b to your computer and use it in GitHub Desktop.
- (id)init
{
if (self = [super init])
{
[self addObserver:self forKeyPath:@"isDirty" options:0 context:NULL];
}
return self;
}
- (void)dealloc
{
[self removeObserver:self forKeyPath:@"isDirty"];
}
- (BOOL)loadData
{
// Load the data, then if successful:
isDirty = NO;
return YES;
}
- (BOOL)saveData
{
if (!self.isDirty)
{
return YES;
}
// Save the data, then if successful:
isDirty = NO;
return YES;
}
// isDirty is dependant on ALL of our declared property.
+ (NSSet *)keyPathsForValuesAffectingIsDirty
{
unsigned int num_props;
objc_property_t *prop_list = class_copyPropertyList(self, &num_props);
NSMutableSet * propSet = [NSMutableSet set];
for( unsigned int i = 0; i < num_props; i++ )
{
NSString * propName = [NSString stringWithFormat:@"%s", property_getName(prop_list[i])];
if(![propName isEqualToString:@"isDirty"] )
{
[propSet addObject:propName];
}
}
free(prop_list);
return propSet;
}
// If any of our declared properties are changed, this will be called so set isDirty to true.
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"isDirty"])
{
isDirty = YES;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment