我尝试了其他帖子中的各种建议,但似乎仍然无法正常工作。
这是我的工作流程。
AppDelegate.m
#import CustomObject.h // cocoaAsyncSocket wrapper with delegates
- create customObject[[alloc] init];
mainViewController.m
- (IBAction)connectDisconnect
{
// Access our custom object inside the TPAppDelegate class object.
TPAppDelegate *appDelegate = (TPAppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate.customObject connectToIP:host port:port timeout:10.0];
customObject.m
#import mainViewController.h
// custom object delegate
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
// Access methods and properties inside 'mainViewController' class object.
mainViewController *mainView = (mainViewController *)[UIApplication sharedApplication];
// call method
[mainView textViewLog:@"Hello"];
.
.
}
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIApplication textViewLog:]: unrecognized selector sent to instance 0x188750'
目的是让我的customObject在mainViewController中调用一个方法。
我想念什么?
还是我将其完全错了?
最佳答案
当您在此行中询问[UIApplication sharedApplication]
时
mainViewController *mainView = (mainViewController *)[UIApplication sharedApplication];
你有UIApplication实例。当然不是
mainViewController
。我在这里看到一些解决方案:
将指向mainViewController的指针传递给customObject中的方法
实现委托模式:定义CustomObjectDelegate协议,将委托属性添加到CustomObject,将mainViewController设置为委托,并使用CustomObject中的mainViewController和委托。
如果委托已经在CustomObject中用于其他用途,则可以创建委托的模拟对象(例如,由于UITableView具有委托和dataSource)
在应用程序委托类中创建一些属性(即
mainViewController
),并将mainViewController设置为该属性。比起任何地方,您都可以要求应用程序委托为[[UIApplication sharedApplication] delegate]
,并像mainViewController
一样获得[[[UIApplication sharedApplication] delegate] mainViewController]
。关于iphone - 如何从自定义对象访问mainViewController方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8082111/