From 5b4347661a29d1b191e21dcce4564af533613155 Mon Sep 17 00:00:00 2001 From: Anton Holmquist Date: Wed, 12 Jun 2013 16:05:33 +0200 Subject: [PATCH] Changed timeout timer from NSTimer to GCD timer to avoid retain cycle. --- SocketIO.h | 2 +- SocketIO.m | 46 +++++++++++++++++++++++++++++++++------------- 2 files changed, 34 insertions(+), 14 deletions(-) diff --git a/SocketIO.h b/SocketIO.h index 9624629..72787a0 100755 --- a/SocketIO.h +++ b/SocketIO.h @@ -79,7 +79,7 @@ typedef enum { // heartbeat NSTimeInterval _heartbeatTimeout; - NSTimer *_timeout; + dispatch_source_t _timeout; NSMutableArray *_queue; diff --git a/SocketIO.m b/SocketIO.m index b4d8164..69d69d8 100755 --- a/SocketIO.m +++ b/SocketIO.m @@ -359,6 +359,11 @@ - (void) removeAcknowledgeForKey:(NSString *)key - (void) onTimeout { + if (_timeout) { + dispatch_source_cancel(_timeout); + _timeout = NULL; + } + DEBUGLOG(@"Timed out waiting for heartbeat."); [self onDisconnect:[NSError errorWithDomain:SocketIOError code:SocketIOHeartbeatTimeout @@ -368,16 +373,29 @@ - (void) onTimeout - (void) setTimeout { DEBUGLOG(@"start/reset timeout"); - if (_timeout != nil) { - [_timeout invalidate]; - _timeout = nil; + if (_timeout) { + dispatch_source_cancel(_timeout); + _timeout = NULL; } - _timeout = [NSTimer scheduledTimerWithTimeInterval:_heartbeatTimeout - target:self - selector:@selector(onTimeout) - userInfo:nil - repeats:NO]; + _timeout = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, + 0, + 0, + dispatch_get_main_queue()); + + dispatch_source_set_timer(_timeout, + dispatch_time(DISPATCH_TIME_NOW, _heartbeatTimeout * NSEC_PER_SEC), + 0, + 0); + + __weak SocketIO *weakSelf = self; + + dispatch_source_set_event_handler(_timeout, ^{ + [weakSelf onTimeout]; + }); + + dispatch_resume(_timeout); + } @@ -556,9 +574,9 @@ - (void) onDisconnect:(NSError *)error [_queue removeAllObjects]; // Kill the heartbeat timer - if (_timeout != nil) { - [_timeout invalidate]; - _timeout = nil; + if (_timeout) { + dispatch_source_cancel(_timeout); + _timeout = NULL; } // Disconnect the websocket, just in case @@ -768,8 +786,10 @@ - (void) dealloc _transport = nil; - [_timeout invalidate]; - _timeout = nil; + if (_timeout) { + dispatch_source_cancel(_timeout); + _timeout = NULL; + } _queue = nil; _acks = nil;