Skip navigation.
 
mlStatic in Subclasses
FROM : Justin Giboney
DATE : Thu Mar 27 21:44:17 2008

I need to create a series of classes that implement the Singleton 
design pattern. These classes have a lot of similar methods (I am 
trying to create a series of DAOs see: http://en.wikipedia.org/wiki/Data_Access_Object)
.

I was thinking that it would be best to create a super class, and a 
series of subclasses to that super class. The problem I am running 
upon is that the Singleton pattern requires a static variable.

How can I get a variable that is static to each subclass, but that is 
declared in the super class?

for example I tried this.

/*-------------------------------------------------------------
#import <Cocoa/Cocoa.h>

@interface SuperClass : NSObject {
}
- (void) addToMyVar;
- (int) getMyVar;
@end
   
@implementation SuperClass
static int MyVar = 0;
       
- (void) addToMyVar {
   ++MyVar;
}
   
- (int) getMyVar {
   return MyVar;
}
@end

@interface SubClass1 : SuperClass {
}
@end
@implementation SubClass1
@end

@interface SubClass2 : SuperClass {
}
@end
@implementation SubClass2
@end

int main(int argc, char *argv[])
{

   SubClass1 *mySubClass1 = [[SubClass1 alloc] init];
   SubClass2 *mySubClass2 = [[SubClass2 alloc] init];
   NSLog(@"1 before = %i", [mySubClass1 getMyVar]);
   NSLog(@"2 before = %i", [mySubClass2 getMyVar]);
   [mySubClass1 addToMyVar];
   NSLog(@"1 after 1 = %i", [mySubClass1 getMyVar]);
   NSLog(@"2 after 1 = %i", [mySubClass2 getMyVar]);
   [mySubClass2 addToMyVar];
   NSLog(@"1 after 2 = %i", [mySubClass1 getMyVar]);
   NSLog(@"2 after 2 = %i", [mySubClass2 getMyVar]);

   return NSApplicationMain(argc,  (const char **) argv);
}


----------------------------------*/

which outputs the following

2008-03-27 14:34:31.040 TimeKeeper[790:10b] 1 before = 0
2008-03-27 14:34:31.045 TimeKeeper[790:10b] 2 before = 0
2008-03-27 14:34:31.046 TimeKeeper[790:10b] 1 after 1 = 1
2008-03-27 14:34:31.047 TimeKeeper[790:10b] 2 after 1 = 1
2008-03-27 14:34:31.048 TimeKeeper[790:10b] 1 after 2 = 2
2008-03-27 14:34:31.049 TimeKeeper[790:10b] 2 after 2 = 2

I want it so that it outputs

2008-03-27 14:34:31.040 TimeKeeper[790:10b] 1 before = 0
2008-03-27 14:34:31.045 TimeKeeper[790:10b] 2 before = 0
2008-03-27 14:34:31.046 TimeKeeper[790:10b] 1 after 1 = 1
2008-03-27 14:34:31.047 TimeKeeper[790:10b] 2 after 1 = 0
2008-03-27 14:34:31.048 TimeKeeper[790:10b] 1 after 2 = 1
2008-03-27 14:34:31.049 TimeKeeper[790:10b] 2 after 2 = 1

Thank you,

Justin Giboney

Related mailsAuthorDate
mlStatic in Subclasses Justin Giboney Mar 27, 21:44
mlRe: Static in Subclasses Ken Thomases Mar 27, 22:01
mlRe: Static in Subclasses Hamish Allan Mar 27, 22:05
mlRe: Static in Subclasses Troy Stephens Mar 27, 22:12
mlRe: Static in Subclasses Jon Gordon Mar 28, 02:47