Skip to content

Instantly share code, notes, and snippets.

@advantis
Created July 29, 2013 11:10
Show Gist options
  • Save advantis/6103636 to your computer and use it in GitHub Desktop.
Save advantis/6103636 to your computer and use it in GitHub Desktop.
Simple NSManagedObject update observer
//
// Copyright © 2013 Yuri Kotov
//
#import <Foundation/Foundation.h>
typedef void(^ADVManagedObjectHandler)(id object);
@interface ADVManagedObjectController : NSObject
@property (readonly, nonatomic) NSManagedObject *object;
@property (strong, nonatomic) ADVManagedObjectHandler handler;
- (instancetype) initWithObject:(NSManagedObject *)object;
@end
//
// Copyright © 2013 Yuri Kotov
//
#import "ADVManagedObjectController.h"
@interface ADVManagedObjectController ()
@property (strong, nonatomic) NSManagedObject *object;
@end
@implementation ADVManagedObjectController
- (instancetype) initWithObject:(NSManagedObject *)object
{
if ((self = [super init]))
{
_object = object;
[self startNotifying];
}
return self;
}
- (void) startNotifying
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(contextDidChange:)
name:NSManagedObjectContextObjectsDidChangeNotification
object:self.object.managedObjectContext];
}
- (void) stopNotifying
{
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSManagedObjectContextObjectsDidChangeNotification
object:self.object.managedObjectContext];
}
- (void) contextDidChange:(NSNotification *)notification
{
if (self.handler)
{
NSSet *update = notification.userInfo[NSUpdatedObjectsKey];
if ([update containsObject:self.object]) self.handler(self.object);
}
}
- (void) dealloc
{
[self stopNotifying];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment