Last active
November 9, 2020 02:52
-
-
Save msealand/b90e621ad5420bc4f2bf to your computer and use it in GitHub Desktop.
Asynchronous version of NSBlockOperation
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
#import <Foundation/Foundation.h> | |
typedef void(^AsyncBlock)(dispatch_block_t completionHandler); | |
@interface AsyncBlockOperation : NSOperation | |
@property (nonatomic, readonly, copy) AsyncBlock block; | |
+ (instancetype)asyncBlockOperationWithBlock:(AsyncBlock)block; | |
- (instancetype)initWithAsyncBlock:(AsyncBlock)block; | |
@end | |
@interface NSOperationQueue (AsyncBlockOperation) | |
- (void)addAsyncOperationWithBlock:(AsyncBlock)block; | |
@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
#import "AsyncBlockOperation.h" | |
@interface AsyncBlockOperation () { | |
BOOL _finished; | |
BOOL _executing; | |
} | |
@property (nonatomic, copy) AsyncBlock block; | |
@end | |
@implementation AsyncBlockOperation | |
+ (instancetype)asyncBlockOperationWithBlock:(AsyncBlock)block { | |
return [[AsyncBlockOperation alloc] initWithAsyncBlock:block]; | |
} | |
- (instancetype)initWithAsyncBlock:(AsyncBlock)block { | |
if (self = [super init]) { | |
self.block = block; | |
} | |
return self; | |
} | |
- (void)start { | |
[self willChangeValueForKey:@"isExecuting"]; | |
_executing = YES; | |
[self didChangeValueForKey:@"isExecuting"]; | |
self.block(^{ | |
[self willChangeValueForKey:@"isExecuting"]; | |
_executing = NO; | |
[self didChangeValueForKey:@"isExecuting"]; | |
[self willChangeValueForKey:@"isFinished"]; | |
_finished = YES; | |
[self didChangeValueForKey:@"isFinished"]; | |
}); | |
} | |
- (BOOL)isFinished { | |
return _finished; | |
} | |
- (BOOL)isExecuting { | |
return _executing; | |
} | |
- (BOOL)isAsynchronous { | |
return YES; | |
} | |
@end | |
@implementation NSOperationQueue (AsyncBlockOperation) | |
- (void)addAsyncOperationWithBlock:(AsyncBlock)block { | |
[self addOperation:[AsyncBlockOperation asyncBlockOperationWithBlock:block]]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That was very useful! Thanks and greetings from Catalonia 😊