类方法访问静态变量

static int gCounter;

@implementation Fraction

+(Fractoin *)allocF

{

  extern int gCounter;//由于gCounter定义在该文件中,此行定义可省略;

  ++gCounter;

  return  [Fraction alloc];

}

+(int)count

{

  extern int gCounter;//由于gCounter定义在该文件中,此行定义可省略;

  return gCounter;

}

@end

 

#import "Fraction"

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

{

  @autoreleasepool{

     Fraction *a, *b, *c;

     NSLog(@"Fractions allocted: %i", [Fraction count]);

     a = [[Fraction allocF] init];

     b = [[Fraction allocF] init];

     c = [[Fraction allocF] init];

     NSLog(@"Fractions allocted: %i", [Fraction count]);

  }

  return 0;

}

 

输出:

Fraction allocated:0

Fraction allocated:3

posted @ 2012-12-21 10:57  gagag  阅读(366)  评论(0编辑  收藏  举报