Skip to content

Instantly share code, notes, and snippets.

@xilin
Forked from berzniz/NSObject+Debounce.h
Created March 10, 2018 12:21
Show Gist options
  • Save xilin/244347f051016645f8777b0a1bcbd667 to your computer and use it in GitHub Desktop.
Save xilin/244347f051016645f8777b0a1bcbd667 to your computer and use it in GitHub Desktop.
Debounce method for Objective C
@interface NSObject (Debounce)
- (void)debounce:(SEL)action delay:(NSTimeInterval)delay;
@end
@implementation NSObject (Debounce)
- (void)debounce:(SEL)action delay:(NSTimeInterval)delay
{
__weak typeof(self) weakSelf = self;
[NSObject cancelPreviousPerformRequestsWithTarget:weakSelf selector:action object:nil];
[weakSelf performSelector:action withObject:nil afterDelay:delay];
}
@end
@xilin
Copy link
Author

xilin commented Mar 10, 2018

We should use weakSelf in line 7.

If we use strong self, runloop will retain current object; and if running of cancelPreviousPerformRequestsWithTarget:selector:object: release current object, the next line of code will cause crash.

See a more detail explain here in Chinese.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment