문제

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?

도움이 되었습니까?

해결책

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

다른 팁

You are passing a NSString object where a NSData object is expected. However I don't see any reason to append it to the data that you have just created, since it's empty !! So this would be fine:

stringArrayFromTextField1 = [[NSString alloc] initWithString:[textfield1 text]];
bufferToSend= [[NSKeyedArchiver archivedDataWithRootObject: stringArrayFromTextField1] mutableCopy];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top