Search code examples
iosobjective-cappendnsmutabledata

can't append data to NSMutableData getting segmentation fault 11


here´s the question, I'm receiving data from 2 textfields and I want to append that data into a mutableData to obtain just 1 array and send it through OutputStream. here´s the code

I declared as global variable the next

NSMutableData* bufferToSend;

at the init method I did the next:

bufferToSend = [[NSMutableData alloc] initWithCapacity:0];

at the method where I send the info:

NSString* stringArrayFromTextField1;
[bufferToSend initWithCapacity:0];
stringArrayFromTextField1 = [[NSString alloc] initWithString:[textfield1 text]];
[bufferToSend appendData:stringArrayFromTextField1]; //here gives me segmentation fault

When the code tries to executes the append it get crash am I missing something?


Solution

  • There are several errors/issues in your code:

    • [bufferToSend initWithCapacity:0]; for the already initialized object makes no sense.
    • The [[NSString alloc] initWithString:...] call is completely unnecessary, as [textfield1 text] is already a string.
    • appendData: expects NSData, not NSString. This is probably causing the crash. (Did the compiler not display a warning about incompatible types?)

    The code then reduces to:

    NSMutableData* bufferToSend;
    bufferToSend = [[NSMutableData alloc] initWithCapacity:0];
    
    NSData *dataFromTextField = [[textfield1 text] dataUsingEncoding:NSUTF8StringEncoding];
    [bufferToSend appendData:dataFromTextField];