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.

@interface MyThingy : NSObject {

    unsigned int thisInstanceNumber;

@property (readonly) unsigned int thisInstanceNumber;


static unsigned int totalInstances = 0;

@implementation MyThingy

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


    unsigned int thisInstanceNumber = totalInstances;

    return self;

@synthesize thisInstanceNumber;

No comments:

Post a Comment