-
-
Save xilin/244347f051016645f8777b0a1bcbd667 to your computer and use it in GitHub Desktop.
Debounce method for Objective C
This file contains hidden or 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
@interface NSObject (Debounce) | |
- (void)debounce:(SEL)action delay:(NSTimeInterval)delay; | |
@end |
This file contains hidden or 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
@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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.