iJazJaz
iJazJaz

Reputation: 45

How to call a function for all views on load in objective-c?

I have a singleton and it have a function -(void)repair;
I can write [Manager repair]; in every view controller in viewDidLoad, But since I have alot of view controllers I want that function to be called automatically without having to write it manually.

Is That possible, or the code that required for this method is going to take longer time than calling the method in each view?

NOTE: the reason I want to do this is to be able to enable and disable the function anytime I require without having to go back and delete it from each View.

Upvotes: 0

Views: 854

Answers (2)

cekisakurek
cekisakurek

Reputation: 2474

you can swizzle UIViewController viewDidLoad method and put the repair call there. Take a look at http://nshipster.com/method-swizzling/

Upvotes: 0

Jack Cox
Jack Cox

Reputation: 3300

I see two ways to accomplish this:

  1. Create a subclass of UIViewController and implement repair in that class and have that classes viewDidLoad call self.repair. If you're using a mix of UIViewControllers, UITableViewControllers, and UICollectionView controllers, you may need to subclass each of those. Then have each of your view controllers extend the subclass rather than extending UIViewController directly. Then just make sure you're calling super.viewDidLoad in the viewDidLoad (which you should be doing anyway)
  2. Method swizzle viewDidLoad, but that could get ugly pretty fast.

Upvotes: 1

Related Questions