2

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];

2 Answers 2

3

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];
Sign up to request clarification or add additional context in comments.

4 Comments

Shouldn't you release val after adding it to arrayIP?
You don't need to, as val is already auto-released by using the class constructor.
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 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 ?
0

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

2 Comments

Can you take me an example please?
@zp26 Laurent's answer has an example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.