views:

57

answers:

2

Some methods of my class need to know how many times the class has been loaded. Do I need a Singleton for this, or are there other ways to do this? Are there static variables that I can attach to the class and then just increment them every time a viewDidLoad?

When the application starts, that value is resetted (=0). I'm not such a big singleton-friend, since that's such a big overhead of methods in objective-c ;)

+1  A: 

By "how many times the class has been loaded", I presume you mean how many objects of that class have been initialized? The class itself is only loaded once.

static NSUInteger numberOfInitializations = 0;

- (id)init
{
    self = [super init];
    if (self)
    {
        ++numberOfInitializations;
        // other stuff
    }
    return self;
}

- (void)someOtherMethodThatNeedsToKnow
{
    NSLog(@"Current count is %d", numberOfInitializations);
}

-[UIViewController viewDidLoad] may be what you want, but bear in mind that views can be unloaded if they're not showing when memory runs short.

Also bear in mind if you're using views that if you load them from a NIB you need to override -initWithCoder:, whereas if they're created programmatically it's -initWithFrame:.

hatfinch
+1  A: 

If you are after how many times a view has been loaded (displayed) then keep reading :)

The load might happen just once (even if you navigate to and fro a form). If you are after how many time a view appears just create a static field and increment its value in viewWillAppear.

static NSUInteger countAppear = 0;

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    countAppear++;
    NSLog(@"CountAppear %d", countAppear);
}
nicktmro