我想从ViewController 2访问ViewController 1中的一个函数。这可以工作(由断点和NSLog输出确认)。但是,当从ViewController 2调用时,访问ViewController 1中定义的对象 nil 。
ViewController 1.h
#import "SRWebSocket.h"
@interface ViewController : UIViewController <UITextFieldDelegate, SRWebSocketDelegate>
@property (nonatomic,strong) SRWebSocket *socket;
-(void)sendMessageToServerWithContent:(NSString *)message;
ViewController 1.m
- (IBAction)connect:(id)sender {
socket.delegate = nil;
socket = nil;
socket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:serverIP_GLOBAL]]];
socket.delegate = self;
}
-(void)sendMessageToServerWithContent:(NSString *)message{
//irrelevant code for question removed
[self.socket send:jsonString];
}
ViewController 2.h
#import "ViewController.h"
@property (nonatomic,strong) ViewController *viewVC;
@interface ContactsTableViewController : UITableViewController
ViewController 2.m
- (void)viewDidLoad {
[super viewDidLoad];
viewVC = [ViewController alloc];
[viewVC sendMessageToServerWithContent:@"Test"];
//When calling from here, the socket object in ViewController 1 is nil
}
答案 0 :(得分:4)
您无法初始化对象,例如:viewVC = [ViewController alloc];
您必须将ViewContoller1的对象传递给ViewContoller2,即
当你在viewcontoller1上推动ViewContoller2时,你已经编写了storyboard deletgate代码
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
ViewController2 *view2=[segue destinationViewController];
view2.viewVC=self; // pass viewcontoller1 object to viewcontoller2
}
在ViewContoller2中你将访问viewVC变量中的viewContoller1对象,你可以像这样直接调用它
- (void)viewDidLoad {
[super viewDidLoad];
[viewVC sendMessageToServerWithContent:@"Test"];
//When calling from here, the socket object in ViewController 1 is nil
}
答案 1 :(得分:3)
您调用viewVC
,即使未正确创建和初始化也是如此。那个不以前的视图控制器就是之前的屏幕。
1.要调用对象的方法,应首先正确初始化它。
viewVC = [[ViewController alloc] init];
你说,在socket
方法中初始化了viewDidLoad
属性。要强制加载视图,请使用loadView
方法,如果您没有意图首先展示视图。
2.如果要使用特定对象,请不要初始化另一个ViewController
。在您的情况下,它应该是第二个控制器所呈现的控制器。
ViewController.m文件中的某个地方,当第二个视图控制器即将出现时:
ViewController2 *second=[[ViewController2 alloc] init];
second.vc1 = self; // now the second controller has a pointer to original object
[self presentViewController:second ...];
segue
- 导航
- (void)prepareForSegue:(UIStoryBoardSegue *)segue
{
ViewController2 *second=(ViewController2 *)segue.destinationViewController;
send.vc1 = self;
}
现在使用ViewController 2
viewDidLoad
方法
- (void)viewDidLoad
{
[super viewDidLoad];
[self.vc1 sendMessageToServerWithContent:@"Test"];
}
<强> UPD 强>
为什么不将套接字保存在单独的singleton对象中?使用起来要简单得多。这就像是:
[[MySpecialSocketManager sharedInstance] sendMessageToServerWithContent:@"Hello, Server!"];
请参阅如何实现单例here