views:

53

answers:

2

Hi, I have a problem with NSMutableArray. In my program i have a lot of variabile "CFSocketRef". i want to save this in NSMutableArray but i can't. Can you help me? Thank and sorry for my english XP

My code:

CFSocketRef     socketAccept;
NSMutableArray  *arrayIP = [[NSMutableArray alloc] init];



self.socketAccept = CFSocketCreateWithNative(NULL,
                                  fd, 
                                  kCFSocketDataCallBack,
                                  AcceptDataCallback, 
                                  &context);

[arrayIP    addObject:(id)self.socketAccept];
A: 

Box the CFSocketRef into an NSValue using the valueWithPointer: method, then put the NSValue into the array.

Dave DeLong
Can you take me an example please?
zp26
@zp26 Laurent's answer has an example.
Dave DeLong
+2  A: 

You can put a CFSocketRef into a NSMutableArray by wrapping it inside a NSValue:

CFSocketRef socketAccept;
NSMutableArray *arrayIP = [[NSMutableArray alloc] init];
socketAccept = ...
NSValue *val = [NSValue valueWithPointer:socketAccept];
[arrayIP addObject:val];

Use pointerValue to retrieve the value:

CFSocketRef socketAccept = (CFSocketRef) [val pointerValue];
Laurent Etiemble
Shouldn't you release val after adding it to arrayIP?
Jim
You don't need to, as val is already auto-released by using the class constructor.
Laurent Etiemble
Of course, the code leaks arrayIP and socketAccept. If they're fixed, then the code is likely to crash because NSValue doesn't retain its pointers. I would just add the CFSocketRef to the array.
tc.
@tc This is just a snippet a code; it is not meant to be perfect. How do you add the CFSocketRef to the array without boxing it ?
Laurent Etiemble