如何从输出套接字连接中创建全局变量

时间:2014-12-21 22:43:48

标签: objective-c global-variables

我想创建包含套接字连接答案的全局变量。 这是我的代码:

- (void)initNetworkCommunication {
        CFReadStreamRef readStream;
        CFWriteStreamRef writeStream;
        CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.0.10", 35000, &readStream, &writeStream);
        self.inputStream = objc_unretainedObject(readStream);
        self.outputStream = objc_unretainedObject(writeStream);
        [self.inputStream setDelegate:self];
        [self.outputStream setDelegate:self];
        [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        [self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

        [self.inputStream open];
        [self.outputStream open];
    }

    -(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
    {
        switch (eventCode) {

            case NSStreamEventOpenCompleted:
                NSLog(@"Połączono\n");
                break;

            case NSStreamEventHasBytesAvailable:
                if (aStream == self.inputStream) {

                    uint8_t buffer[1024];
                    long len;

                    while ([self.inputStream hasBytesAvailable]) {
                        len = [self.inputStream read:buffer maxLength:sizeof(buffer)];
                        if (len > 0) {

                            NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];

                            if (nil != output) {
                                    NSLog(@"%@",output);


                            }

                        }
                    }
                }
                break;

            case NSStreamEventErrorOccurred:
                NSLog(@"Nie można połączyć\n");
                break;

            case NSStreamEventEndEncountered:
                break;

            default:
                break;
        }
    }

我想将输出变量设为全局变量,因此我可以在其他函数中使用它。我想这样做因为我想创造条件 - 每当我发送请求时,控制器回答我并发送“>”符号,这意味着它已准备好接受另一个请求。我想创建仅在“>”时发送的条件出现。我已经为此完成了RegExp,但现在我遇到了在流函数外部访问输出变量的问题。

1 个答案:

答案 0 :(得分:0)

当您将某些内容声明为extern时,您告诉编译器类型和您将在其他位置定义它。在您的情况下,您永远不会定义您的变量。

首先,确保定义:

// in .h you would have:
        extern NSString* const output; // << declaration

// in .m you would have:
        NSString * const output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];  // << definition