使用Objective-C在循环中使用NSMutableString追加字符串

时间:2014-10-16 11:52:46

标签: ios loops nsstring append nsmutablestring

Communicator.h

@interface Communicator : NSObject <NSStreamDelegate> {
@public

   NSMutableString *strServerResponse;    
   ...
}
@property(nonatomic,retain)NSMutableString *strServerResponse;
@end

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委托。 我哪里错了?

1 个答案:

答案 0 :(得分:0)

最后,经过三天的随机努力,我得到了解决方案。我将 NSASCIIStringEncoding 更改为 NSUTF8StringEncoding ,这对我有用!我不知道如何改变这会影响结果。现在,我从服务器获得结果,并在每个循环中保留最后一个字符串。