Created
March 13, 2012 22:44
-
-
Save raheelahmad/2032332 to your computer and use it in GitHub Desktop.
Using initialize to keep track of instances created by the class object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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