Skip to content

Instantly share code, notes, and snippets.

@raheelahmad
Created March 13, 2012 22:44
Show Gist options
  • Save raheelahmad/2032332 to your computer and use it in GitHub Desktop.
Save raheelahmad/2032332 to your computer and use it in GitHub Desktop.
Using initialize to keep track of instances created by the class object
#import <Foundation/Foundation.h>
@interface MyClass : NSObject
@end
@implementation MyClass
static NSMutableArray *instances;
+ (void) initialize {
if (self == [MyClass class]) {
instances = [[NSMutableArray alloc] init];
}
}
+ (id) alloc {
id objCreated = [super alloc];
[instances addObject:objCreated];
NSLog(@"Creating");
return objCreated;
}
+ (void) printInstances {
for (id obj in instances) {
NSLog(@"%@", obj);
}
}
- (void) dealloc {
[instances release];
[super dealloc];
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
MyClass *obj1 = [[MyClass alloc] init];
MyClass *obj2 = [[MyClass alloc] init];
[MyClass printInstances];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment