0

第一个控制器的代码:

 optionscontroller =  [[OptionsViewController alloc] init ];

 [optionscontroller setupSocket];

第二个控制器的代码:

- (void)setupSocket
 {
udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self      delegateQueue:dispatch_get_main_queue()];

NSError *error = nil;

if (![udpSocket bindToPort:0 error:&error])
{
    //  [self logError:FORMAT(@"Error binding: %@", error)];
    return;
}
if (![udpSocket beginReceiving:&error])
{
    //  [self logError:FORMAT(@"Error receiving: %@", error)];
    return;
}

isRunning = YES;
NSLog(@"Udp Echo server started on port %hu", [udpSocket localPort]); }

动作之一:

- (IBAction)testbutton:(id)sender {


NSString *host = @"192.168.1.255";
if ([host length] == 0)
{

    NSLog(@"Address required");

    return;
}


NSString *msg = @"hi";
if ([msg length] == 0)
{
    //[self logError:@"Message required"];
    return;
}

NSData *data = [msg dataUsingEncoding:NSUTF8StringEncoding];
[udpSocket enableBroadcast:YES error:nil ];
[udpSocket sendData:data toHost:host port:port withTimeout:-1 tag:0];



tag++;

}

当我从第一个控制器调用“setupSocket”时,它会启动,但是当我转到 OptionsViewController 并单击按钮时 - 没有任何反应,它的含义是正确的并且它有效,当我从第二个控制器的“视图加载功能”调用“setupSocket”时,一切正常好吧,为什么???

因此,如果不是从目标视图控制器初始化某些方法,则此方法不起作用。我不明白它是怎么发生的?

4

1 回答 1

0

If you are using a XIB with interface builder you need to make sure that you wire the button up to it's action. Do this by right clicking and dragging from your button to your file's owner in the Interface Builder.

Oh also, you need to optionscontroller = [[OptionsViewController alloc] initWithNibName:@"YOURNIBNAMEHERE"];

If you are creating it programmatically (which if you're using IBAction you should not be) then you would use this:

addTarget:action:forControlEvents:

Read here:

http://developer.apple.com/library/ios/#documentation/uikit/reference/UIControl_Class/Reference/Reference.html

于 2012-04-12T18:04:47.567 回答