Skip to content

Instantly share code, notes, and snippets.

@meiwin
Created May 15, 2012 13:32
Show Gist options
  • Save meiwin/2701811 to your computer and use it in GitHub Desktop.
Save meiwin/2701811 to your computer and use it in GitHub Desktop.
Responding to NSManagedObject lifecycle events with automatic callback to simple method naming convention.
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// NSManagedObject+AutoUpdating.h
// Piggie
//
// Created by Meiwin Fu on 14/5/12.
// Copyright (c) 2012 –MwF. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSManagedObject (AutoUpdating)
- (void)updateForKey:(NSString *)key;
- (void)updateForAllKeys;
@end
@interface NSAutoUpdatingManagedObject : NSManagedObject
@end
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// NSManagedObject+AutoUpdater.m
// Piggie
//
// Created by Meiwin Fu on 14/5/12.
// Copyright (c) 2012 –MwF. All rights reserved.
//
#import "NSManagedObject+AutoUpdating.h"
@implementation NSManagedObject (AutoUpdating)
- (void)updateForKey:(NSString *)key;
{
NSString * methodName = nil;
key = [key stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if (key && [key length]) {
methodName = [NSString stringWithFormat:@"updateFor%@%@Change",
[[key substringToIndex:1] uppercaseString],
([key length] > 1 ? [key substringFromIndex:1] : @"")];
}
if (methodName) {
SEL methodSEL = sel_getUid([methodName UTF8String]);
BOOL methodImplemented = [self respondsToSelector:methodSEL];
if (methodImplemented) {
[self performSelector:methodSEL];
}
}
}
- (void)updateForAllKeys;
{
NSEntityDescription * entity = self.entity;
NSArray * props = entity.properties;
for (NSPropertyDescription * prop in props) {
[self updateForKey:prop.name];
}
}
@end
@implementation NSAutoUpdatingManagedObject
- (void)awakeFromFetch;
{
[super awakeFromFetch];
[self updateForAllKeys];
}
- (void)awakeFromInsert;
{
[super awakeFromInsert];
[self updateForAllKeys];
}
- (void)didChangeValueForKey:(NSString *)key;
{
[super didChangeValueForKey:key];
[self updateForKey:key];
}
- (void)didTurnIntoFault;
{
[super didTurnIntoFault];
[self updateForAllKeys];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment