追加字符串,Objective-C的
问题描述:
Communicator.h追加字符串,Objective-C的
Communicator.m
@implementation Communicator
@synthesize strServerResponse;
- (void)setup {
...
strServerResponse = [[NSMutableString alloc] init];
...
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)event {
NSLog(@"Stream triggered.");
NSMutableString *strSuccess = [[NSMutableString alloc]init];
switch(event) {
...
case NSStreamEventHasBytesAvailable: {
if (stream == inputStream) {
NSLog(@"inputStream is ready.");
uint8_t buffer[1024*6];
int len;
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:(1024*6)]; //sizeof(buffer)
if (len > 0) {
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
if (nil != output) {
// NSLog(@"server said: %@", output);
[strSuccess appendString:output];
[strServerResponse appendString:output];
}
}
}
}
break;
}
}
NSLog(@"strServerResponse : %@ ",strServerResponse);
NSLog(@"strSuccess : %@ ", strSuccess);
}
MainFile.m
-(void)viewDidAppear:(BOOL)animated {
communicator = [[Communicator alloc] init];
communicator->host = @"http://SomeURL";
communicator->port = 1234;
[communicator setup];
}
我在连接字符串时遇到了问题。 strServerResponse打印空日志,因为strSuccess不附加上一个值,因为handleEvent委托被多次调用。 我哪里出错了?
答
最后我在三天的随机努力后得到了解决方案。我改变了NSASCIIStringEncoding到NSUTF8StringEncoding这对我来说很神奇!我不知道如何改变这可能会影响结果。现在,我从服务器获得每个循环中保留最后一个字符串的结果。