views:

37

answers:

2

Hey guys,

I want to store a couple of sockets in an ArrayList/NSMutableArray, but the sockets are of type int and NSMutableArray only accepts objects (id). Is there another data type that I can use as a container for sockets? I am not sure how many entries I will have, so I would like the data container to be like an ArrayList.

Thanks!

EDIT: I've tried to send the socket as an NSNumber, but it did not work and caused XCode to crash when I tried to send a message using the socket.

+1  A: 

You can wrap your int in an NSNumber like:

NSNumber *socket = [NSNumber numberWithInt:socketInt];
[myArray addObject:socket];
NSNumber *getSocket = [myArray objectAtIndex:0];
int getSocketInt = [getSocket intValue];

More here

vodkhang
I tried that, but it will not work. XCode crashes =/
hassaanm
So, you should post the code that you tried. Some memory management issue here for sure
vodkhang
Ah, actually you're right. Thanks! I was doing this: [NSThread detachNewThreadSelector:@selector(sendMessage:) toTarget:self withObject:socket]; and socket was an int. I converted it to early.
hassaanm
yeah, just put NSNumber there and wrap out whenever you really need int:)
vodkhang
+6  A: 

You should wrap up your file descriptors in NSFileHandle instances, these will play nice inside collection objects such as NSArray and are designed to wrap around file descriptors such as sockets. They also allow you to use standard Foundation types such as NSData in conjunction with your communication.

int s = socket(AF_INET, SOCK_STREAM, 0);

if (s != -1)
{
    // bind or connect to address

    NSFileHandle *mySock = [[NSFileHandle alloc] initWithFileDescriptor:s closeOnDealloc:YES];

    [myMutableArray addObject:mySock];
}

Note that NSFileHandle also provides convenience methods for accepting connections asynchronously, as well as asynchronous I/O. You can get the original file descriptor back by using the fileDescriptor method.

dreamlax