2014-12-21 57 views
0

我想創建一個全局變量,它將包含來自套接字連接的答案。 這是我的代碼:如何從輸出套接字連接進行全局變量

- (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,但是現在我有訪問輸出變量外流功能的問題。

+0

當我試圖在.h文件中定義輸出 的extern的NSString *輸出 我reciving 2級紅色的錯誤 - https://開頭DL。 dropboxusercontent.com/u/7071011/Zrzut%20ekranu%202014-12-22%20o%2000.38.44.png –

回答

0

當你將某些東西聲明爲extern時,你告訴編譯器類型AND你將在別的地方定義它。在你的情況你永遠不會定義你的變量。

首先,確保它的定義:

// 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