views:

60

answers:

1

I have a problem with threads objectiveC. The line of code below contains the recv block the program waiting for a datum. My intention is to launch a thread parallel to the program so that this statement does not block any application. I put this code in my program but when active switch the program crashes. Enter the code.

-(IBAction)Chat{

    if(switchChat.on){

        buttonInvio.enabled = TRUE;
        fieldInvio.enabled = TRUE;

        [NSThread detachNewThreadSelector:@selector(riceviDatiServer) toTarget:self withObject:nil];  

    }
    else {
        buttonInvio.enabled = FALSE;
        fieldInvio.enabled = FALSE;
    }

-(void)riceviDatiServer{

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];

    int ricevuti;
    NSString *datiRicevuti;
    ricevuti = recv(temp, &datiRicevuti, datiRicevuti.length, 0);
    labelRicezione.text = [[NSString alloc] initWithFormat:@"%s.... %d", datiRicevuti, ricevuti];

    [pool   release];

}
+1  A: 

This part

 NSString *datiRicevuti;
 ricevuti = recv(temp, &datiRicevuti, datiRicevuti.length, 0);

is clearly bad. NSString* is not a C buffer. So you shouldn't pass that to recv. What you should is to recv the data just as in C (see the documentation for recv). Say it's now in void*receivedData and its length is dataLength. Then, convert it to NSString by something like

NSString*dataAsNSString=[[NSString alloc] initWithBytes:receivedData 
                                          length:dataLength encoding:NSISOLatin1StringEncoding];
Yuji
I'm sorry but my problem is not solved, indeed, the program crashes when you enable the statement.I hope it is not misunderstood.Thanks anyway.
zp26
Hi zp26, ok this was not the only problem. Then we need to look for other problems. But remember, we're not psychics, so we don't understand what's going on when you say "enable the statement" or "it crashes". We need more verbose information to figure out what is going on. For example, you can quote the crash report in the post to StackOverflow. It contains a lot of useful information if you can read it. Please try to think what other people need in order to diagnose the problem in your code.
Yuji
I would add to Yuji's comments, when you say "it crashes", that is not enough information. We need to know exactly what kind of crash you get. Is it EXC_BAD_ACCESS or some other error? What line does it happen on?NB even in Yuji's answer, he has not done everything for you. You clearly need to allocate some space for receiveData. You cannot just pass an uninitialised void pointer.
JeremyP
You are quite right either.Excuse me if I was not clear in my posts, but it is one of the first public and then post that I did not know how to move.I also apologize if I have seemed a bit abrupt but I do not speak English very well, my intention was definitely not to attack anyone.Indeed, I thank all of the aid by which I could arrange my schedule.Thank you.
zp26