I am using TCP short connection to send data to a host. When I want to send a data to a host I will instantiate a socket, store the socket instance to an array and then remove it later on when the data is written successfully.
This is how I did it:
- (void)connectAndSendData:(NSData *)data
{
GCDAsyncSocket *asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
[_connectionDataToBeSentMap setObject:data forKey:[NSValue valueWithNonretainedObject:asyncSocket]];
NSError *error;
if(![asyncSocket connectToHost:_host onPort:TCP_COMMUNICATION_PORT withTimeout:TCP_CONNECTION_TIMEOUT error:&error])
{
NSLog(@"TCPShortConnection - failed when attempting to connect to host with IP %@", _host);
}
[_connectionList addObject:asyncSocket];
}
I will disconnect the socket immediately after writing the data. So the connection will be removed afterwards:
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
[_connectionList removeObject:sock];
if(err.code == GCDAsyncSocketConnectTimeoutError)
{
// NSLog(@"TCPShortConnection - on connection timed out");
[_delegate onTCPShortConnectionTimedOut];
}
else
{
// NSLog(@"TCPShortConnection - on disconnection of socket with host %@", _host);
}
}
This line [_connectionList removeObject:sock];
is throwing NSRangeException. And I don't know why. Because I made a test by removing a non existing object in an empty array, no such exception is thrown.
Here's the log:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
*** First throw call stack:
(0x258d9b0b 0x25096dff 0x257ea6d3 0x257ff033 0xfae43 0x1ca94d 0x4ccba7 0x4d8eff 0x4d87f1 0x2560ae0d 0x2560a9fc)
libc++abi.dylib: terminating with uncaught exception of type NSException
The screenshot:
EDIT:
Please take not that this is not 100% occuring.