简体   繁体   中英

Objective-C NSMutableArray of sockets?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM