Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access mainViewController methods from custom object?

I've tried the various suggestions from other posts and still can't seem to get this working properly.

Here is my workflow.

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'

The goal is to get my customObject call a method in the mainViewController.

What am I missing? Or am I going about it completely wrong?

like image 617
Sebastian Dwornik Avatar asked Mar 29 '26 23:03

Sebastian Dwornik


1 Answers

when you ask [UIApplication sharedApplication] in this line

mainViewController *mainView = (mainViewController *)[UIApplication sharedApplication];

you got UIApplication instance. Ofcource it's not a mainViewController.

I see a few solutions here:

  1. pass pointer to your mainViewController to method in customObject
  2. implement delegate pattern: define CustomObjectDelegate protocol, add delegate property to CustomObject, set mainViewController as delegate, work with mainViewController from CustomObject as with it delegate.
  3. If delegate already used in CustomObject for something else, than you could create delegate's analog (for example as UITableView has delegate and dataSource)
  4. create some property (i.e. mainViewController) in your application delegate class and set mainViewController to it. Than from anywhere you could ask application delegate as [[UIApplication sharedApplication] delegate] and get your mainViewController like [[[UIApplication sharedApplication] delegate] mainViewController].
like image 53
yas375 Avatar answered Apr 02 '26 03:04

yas375



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!