Skip to content
This repository has been archived by the owner on Mar 3, 2020. It is now read-only.

Commit

Permalink
Merge pull request #27 from telly/nsobject-category
Browse files Browse the repository at this point in the history
Add NSObject category with a convenient, lazy loaded KVOController
  • Loading branch information
Kimon Tsinteris committed Oct 18, 2014
2 parents bf52f0a + a29baac commit b7fdee7
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
12 changes: 12 additions & 0 deletions FBKVOController/FBKVOController.h
Original file line number Diff line number Diff line change
Expand Up @@ -135,3 +135,15 @@ typedef void (^FBKVONotificationBlock)(id observer, id object, NSDictionary *cha
- (void)unobserveAll;

@end

@interface NSObject (FBKVOController)

/**
@abstract Lazy-loaded FBKVOController for use with any object
@return FBKVOController associated with this object, creating one if necessary
@discussion This makes it convenient to simply create and forget a FBKVOController, and when this object gets dealloc'd, so will the associated controller and the observation info.
*/
@property (nonatomic, strong) FBKVOController *KVOController;
@property (nonatomic, strong) FBKVOController *KVOControllerNonRetaining;

@end
45 changes: 45 additions & 0 deletions FBKVOController/FBKVOController.m
Original file line number Diff line number Diff line change
Expand Up @@ -622,3 +622,48 @@ - (void)unobserveAll
}

@end

#pragma mark NSObject Category -

static void *NSObjectKVOControllerKey = &NSObjectKVOControllerKey;
static void *NSObjectKVOControllerNonRetainingKey = &NSObjectKVOControllerNonRetainingKey;

@implementation NSObject (FBKVOController)

- (FBKVOController *)KVOController
{
id controller = objc_getAssociatedObject(self, NSObjectKVOControllerKey);

// lazily create the KVOController
if (nil == controller) {
controller = [FBKVOController controllerWithObserver:self];
self.KVOController = controller;
}

return controller;
}

- (void)setKVOController:(FBKVOController *)KVOController
{
objc_setAssociatedObject(self, NSObjectKVOControllerKey, KVOController, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (FBKVOController *)KVOControllerNonRetaining
{
id controller = objc_getAssociatedObject(self, NSObjectKVOControllerNonRetainingKey);

if (nil == controller) {
controller = [[FBKVOController alloc] initWithObserver:self retainObserved:NO];
self.KVOControllerNonRetaining = controller;
}

return controller;
}

- (void)setKVOControllerNonRetaining:(FBKVOController *)KVOControllerNonRetaining
{
objc_setAssociatedObject(self, NSObjectKVOControllerNonRetainingKey, KVOControllerNonRetaining, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

0 comments on commit b7fdee7

Please sign in to comment.