Created
July 29, 2013 11:10
-
-
Save advantis/6103636 to your computer and use it in GitHub Desktop.
Simple NSManagedObject update observer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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