zakdances
zakdances

Reputation: 23725

How can I trigger a method on property change?

I have a class tabBarController and every time its selectedIndex property changes, I want to trigger a custom method. How do I accomplish this?

this is how the tabBarController is being declared in the h's instance vars:

BaseViewController *tabBarController;

Upvotes: 0

Views: 206

Answers (4)

Legolas
Legolas

Reputation: 12345

Use delegate method -(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem * )item

Upvotes: 0

unexpectedvalue
unexpectedvalue

Reputation: 6139

Create a setter:

- (void)setSelectedIndex:(NSInteger*)integer
{
    // Do stuff
    selectedIndex=integer;
    // Or: [super setSelectedIndex:integer];
}

Upvotes: 0

larsacus
larsacus

Reputation: 7346

This is a perfect candidate for key-value-observing. Basically, when the value is changed, a notification is fired off and picked up by any observers that you define that want to be observing that value for any changes. When you establish yourself and an observer and implement the observeValueForKeyPath: method, you can have it fire off whatever method you would like.

Here is a good starting point: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html#//apple_ref/doc/uid/10000177-BCICJDHA

A little daunting at first, but basically magic when used properly.

Edit: didn't see that it was simple a UITabBarController. Yes, simply use the delegate methods. KVO is overkill for this.

Upvotes: 3

CodaFi
CodaFi

Reputation: 43330

Use UITabBar's -(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem * )item method to determine the index of the tab and consequently the method you wish to call.

Upvotes: 5

Related Questions