Sjakelien
Sjakelien

Reputation: 2317

Prohibit viewdidload on subviews

I have this myViewController, that instantiates instances of itself.

Currently, I have a UIButton, that triggers the method

-(void)somethingImportant

However, I want that somethingImportant to happen during the ViewDidLoad, so I don't have to push that button.

But if I put somethingImportant in the ViewDidLoad of myViewController, it is recursively called as many times I have a subview of myViewController.

I tried to put somethingImportant in the application didFinishLaunchingWithOptions: of my app delegate, but somehow that does't work either.

EDIT

So here's the code that might be relevant. I have this UIScrollView with a lot of subviews of myViewController:

- (void)configureScrollView
{
    for (int i = 0; i < [self.childViewControllers count]; i++) {
        ...
        myViewController * theSubview =[self.childViewControllers objectAtIndex:i];
       ....
        [theScrollView addSubview:[theSubview view]];
    }

}

What is the best approach to make sure that somethingImportant is called only once?

Upvotes: 0

Views: 52

Answers (2)

Hamish
Hamish

Reputation: 80951

I have this class, that instantiates instances of itself.

This inherently sounds like a bad idea and can easily lead to recursion if you're not careful. Therefore I would suggest you rethink your logic. If you need multiple instances of a class, you should be managing those instances from outside that class, not from within.

However, if you're still insistent on doing this - you can do something similar to what sschale suggests and use a variable to keep track of whether you've called your method or not.

The thing is you'll need to define this variable as static in order for it to be stored at class scope, not instance scope.

For example:

static BOOL firstCalled = NO;

- (void)viewDidLoad {
    [super viewDidLoad];

    if (!firstCalled) {
        firstCalled = YES;
        [self foo];
    }
}

Upvotes: 1

sschale
sschale

Reputation: 5188

Each subclass should be calling [super viewDidLoad], on up the chain, so that code really should only be called once.

However, if you need to make sure it executes only once, add @property (nonatomic) BOOL runOnce; to that file's interface, and then in -(viewDidLoad) do:

if(!self.runOnce) {
    //all code that is only run once
    self.runOnce = YES;
}

Upvotes: 0

Related Questions