Skip to content

Instantly share code, notes, and snippets.

@yannxou
Created May 5, 2015 08:41
Show Gist options
  • Save yannxou/3c4ea943909174ed2792 to your computer and use it in GitHub Desktop.
Save yannxou/3c4ea943909174ed2792 to your computer and use it in GitHub Desktop.
NSThread sample skeleton
@interface ThreadSample ()
@property (nonatomic, strong) NSThread *thread;
@end
@implementation ThreadSample
#pragma mark - Private
- (NSThread*)thread {
if (!_thread) {
_thread = [[NSThread alloc] initWithTarget:self selector:@selector(runloop) object:nil];
}
return _thread;
}
- (void)runloop {
// Init
// Loop
while (![self.thread isCancelled]) {
// TODO: some stuff
// remember always update UI objects on the main thread:
// [self performSelector:@selector(updateUI:) onThread:[NSThread mainThread] withObject:nil waitUntilDone:NO];
sleep(1);
}
// De-init
self.thread = nil;
}
#pragma mark - Public
- (void)start {
if (![self.thread isExecuting]) {
[self.thread start];
}
}
- (void)stop {
if ([self.thread isExecuting]) {
[self.thread cancel];
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment