2010-08-13

Objective-C counting the number of instances of a class (objects).

Stolen from http://www.techotopia.com/index.php/Writing_Objective-C_Class_Methods.

In my example below I do not create a class method for accessing the total number of instances. That is not what I wanted at this moment. See above link for an example of that.

All I wanted was for each object to carry around a value that said what object number it was.

MyThingy.h
@interface MyThingy : NSObject {

    unsigned int thisInstanceNumber;
}

@property (readonly) unsigned int thisInstanceNumber;

@end

MyThingy.m
static unsigned int totalInstances = 0;

@implementation MyThingy

- (id) init {
    self = [super init];

    totalInstances++;

    unsigned int thisInstanceNumber = totalInstances;

    return self;
}

@synthesize thisInstanceNumber;
@end

No comments:

Post a Comment