2014-10-16 63 views
0

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委託被多次調用。 我哪裏出錯了?

回答

0

最後我在三天的隨機努力後得到了解決方案。我改變了NSASCIIStringEncodingNSUTF8StringEncoding這對我來說很神奇!我不知道如何改變這可能會影響結果。現在,我從服務器獲得每個循環中保留最後一個字符串的結果。