如何使用textfield在socket中设置IP

时间:2015-07-01 13:17:28

标签: ios objective-c sockets

我有一个Socket的程序,原本在这个程序里面都预先编写了IP程序,现在的代码如下:

CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)@"ip address", port, &readStream, &writeStream);

这只能是一个固定的IP地址,如果我想改变使用textfield输入IP。 我有两个viewcontroller socketViewsetViewcontrollertextfield被放置setViewcontrollersocketview进程是套接字的使用。 textfieldNSString的价值:

NSString *ip = TxtIP.text;

我的想法是在NSString *dstIP

中定义socketView.m
NSString *dstAddress; 
-(void) initNetworkCommunication{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)dstAddress, 8080, &readStream, &writeStream);
inputStream = ( NSInputStream *)CFBridgingRelease(readStream);
outputStream = ( NSOutputStream *) CFBridgingRelease(writeStream);

[inputStream setDelegate:self];
[outputStream setDelegate:self];

[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

[inputStream open];
[outputStream open];}

然后在setviewcontrolle.m内设置dstIP = TxtIP.text。 但我知道这不是直接设置的,我该如何修改呢?

1 个答案:

答案 0 :(得分:0)

我想我找到了解决问题的方法! 我使用NSUserDefaults来存储textfield值:

NSString *IPaddress = [textfield text];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:IPaddress forKey:@"IPaddress"];
[defaults synchronize];

然后SocketView阅读:

NSString *dstAddress;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *IPaddress = [defaults objectForKey:@"IPaddress"];
dstAddress=IPaddress;