Skip to content
This repository was archived by the owner on May 14, 2024. It is now read-only.

Commit 5b43476

Browse files
Changed timeout timer from NSTimer to GCD timer to avoid retain cycle.
1 parent 79fac8e commit 5b43476

File tree

2 files changed

+34
-14
lines changed

2 files changed

+34
-14
lines changed

SocketIO.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ typedef enum {
7979

8080
// heartbeat
8181
NSTimeInterval _heartbeatTimeout;
82-
NSTimer *_timeout;
82+
dispatch_source_t _timeout;
8383

8484
NSMutableArray *_queue;
8585

SocketIO.m

Lines changed: 33 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,11 @@ - (void) removeAcknowledgeForKey:(NSString *)key
359359

360360
- (void) onTimeout
361361
{
362+
if (_timeout) {
363+
dispatch_source_cancel(_timeout);
364+
_timeout = NULL;
365+
}
366+
362367
DEBUGLOG(@"Timed out waiting for heartbeat.");
363368
[self onDisconnect:[NSError errorWithDomain:SocketIOError
364369
code:SocketIOHeartbeatTimeout
@@ -368,16 +373,29 @@ - (void) onTimeout
368373
- (void) setTimeout
369374
{
370375
DEBUGLOG(@"start/reset timeout");
371-
if (_timeout != nil) {
372-
[_timeout invalidate];
373-
_timeout = nil;
376+
if (_timeout) {
377+
dispatch_source_cancel(_timeout);
378+
_timeout = NULL;
374379
}
375380

376-
_timeout = [NSTimer scheduledTimerWithTimeInterval:_heartbeatTimeout
377-
target:self
378-
selector:@selector(onTimeout)
379-
userInfo:nil
380-
repeats:NO];
381+
_timeout = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,
382+
0,
383+
0,
384+
dispatch_get_main_queue());
385+
386+
dispatch_source_set_timer(_timeout,
387+
dispatch_time(DISPATCH_TIME_NOW, _heartbeatTimeout * NSEC_PER_SEC),
388+
0,
389+
0);
390+
391+
__weak SocketIO *weakSelf = self;
392+
393+
dispatch_source_set_event_handler(_timeout, ^{
394+
[weakSelf onTimeout];
395+
});
396+
397+
dispatch_resume(_timeout);
398+
381399
}
382400

383401

@@ -556,9 +574,9 @@ - (void) onDisconnect:(NSError *)error
556574
[_queue removeAllObjects];
557575

558576
// Kill the heartbeat timer
559-
if (_timeout != nil) {
560-
[_timeout invalidate];
561-
_timeout = nil;
577+
if (_timeout) {
578+
dispatch_source_cancel(_timeout);
579+
_timeout = NULL;
562580
}
563581

564582
// Disconnect the websocket, just in case
@@ -768,8 +786,10 @@ - (void) dealloc
768786

769787
_transport = nil;
770788

771-
[_timeout invalidate];
772-
_timeout = nil;
789+
if (_timeout) {
790+
dispatch_source_cancel(_timeout);
791+
_timeout = NULL;
792+
}
773793

774794
_queue = nil;
775795
_acks = nil;

0 commit comments

Comments
 (0)