Skip to content

Added optional callback to removeDelegate #30

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions DelegateDispatch/S2MDelegateDispatcher.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
//

#import <Foundation/Foundation.h>

typedef void (^DelegateDispatcherCallback)();

@protocol S2MDelegateDispatcher
@property (nonatomic, readonly) NSUInteger delegateCount;

Expand All @@ -21,6 +24,10 @@
Removes a delegate from the internal list of delegates.
*/
- (void)removeDelegate:(id)delegate;
/**
Removes a delegate from the internal list of delegates, calls callback in case the last delegate was removed.
*/
- (void)removeDelegate:(id)delegate noDelegatesLeftCallback:(DelegateDispatcherCallback) callback;

- (BOOL)isRegisteredAsDelegate:(id)delegate;
@end
Expand Down
23 changes: 18 additions & 5 deletions DelegateDispatch/S2MDelegateDispatcher.m
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,18 @@ - (void)addDelegate:(id)delegate
}

- (void)removeDelegate:(id)delegate
{
[self removeDelegate:delegate noDelegatesLeftCallback:nil];
}

- (void)removeDelegate:(id)delegate noDelegatesLeftCallback:(DelegateDispatcherCallback) callback
{
dispatch_sync(self.serialQueue, ^{
[self.delegates removeObject:delegate];
if (0 == [self unsafeDelegatesCount] && callback)
{
callback();
}
});
}

Expand Down Expand Up @@ -79,15 +88,19 @@ - (NSString *)description

- (NSUInteger)delegateCount
{
NSArray *__block allDelegates;
__block NSUInteger count;
dispatch_sync(self.serialQueue, ^{
allDelegates = [self.delegates allObjects];
count = [self unsafeDelegatesCount];
});
// the count of an NSHashTable does not update if a collection member has been deallocated and therefore zeroed out. Hence we need to count allObjects to get the correct number.
return [allDelegates count];
return count;
}


/** MUST be used from inside self.serialQueue only! */
- (NSUInteger)unsafeDelegatesCount
{
// the count of an NSHashTable does not update if a collection member has been deallocated and therefore zeroed out. Hence we need to count allObjects to get the correct number.
return [self.delegates allObjects].count;
}

#pragma mark - HOM

Expand Down