lyn87
lyn87

Reputation: 49

How to run method from another class

In TabBarViewController class, I have startUpdateNPendingMessagesTimer method which run a NSTimer

I have also timerStop to stop this NSTimer with invalidate method

-(void)startUpdateNPendingMessagesTimer {
    NSLog(@"Starting UpdateNPendingMessagesTimer");
    checkNPendingMessagesTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(onUpdateNPendingMessages:) userInfo:nil repeats:YES];
}
-(void)timerStop
{
    [checkNPendingMessagesTimer invalidate];
    checkNPendingMessagesTimer = nil;
}

In another class settingsViewController, I have a button, which actually have to activate the timerStop method.

     -(IBAction)deconnexion {    ....        
    }

What should I write in the button action to activate the timerStop method ? In other words, how to activate a method from another class in objective C ?

Upvotes: 0

Views: 60

Answers (2)

Mathieu
Mathieu

Reputation: 96

You can use the Notification Center to communicate between two unrelated classes.

First in your ViewDidLoad of your TabBarViewController class register to a specific notification (identified by a "name") with the code below:

 [[NSNotificationCenter defaultCenter] addObserver:self
        selector:@selector(timerStop) 
        name:@"aNameOfaNotification"
        object:nil];

Then in your "deconnexion" method you just need to post a notification of the same name:

[[NSNotificationCenter defaultCenter] postNotificationName:@"aNameOfaNotification" 
    object:nil];

Every class who observe that Notification Name will fire the local method specified in the selector: argument, in this case: timerStop.

Be careful if you are not using ARC, you may also need to unregister your TabBarViewController class when it is discarded by adding the following code in this class:

-(void) dealloc {
      [[NSNotificationCenter defaultCenter] removeObserver:self];
      [super dealloc];
}

(You can also use: viewWillAppear / viewWillDisappear for your addObserver/removeObserver code)

Bonne chance!

Upvotes: 0

pdeschain
pdeschain

Reputation: 1421

There are a bunch of options:

  • Notification via Notification center
  • Lambda callback (in objc terms it's called "block") - pass it to your object that runs timer and store it. Invoke it when appropriate
  • use the omnipresent (in cocoa) pattern of Delegation - create a delegate object and pass it to your timer-containing class. Call methods of this object when appropriate.

I'd go with block/lambda, as it is clean, efficient, has less overhead than other solutions and saves typing (yay!).

Upvotes: 2

Related Questions