object-c学习:类的静态成员
初学咋练难免惹笑话,有错误处拍砖哈 :-)
object-c中并没有提供类静态变量,只能以文件作用域的static变量代替,然后由类的成员函数来操作,这样设计的目的,还没想明白,先mark下以后再说把。下面提供个例子:
代码
#import <Foundation/Foundation.h>
static int sTier_count = 0;
@interface Tier : NSObject
{
@private
int tier_num;
}
@end
@implementation Tier
- (id) init
{
if (self = [super init]) {
sTier_count++;
tier_num = sTier_count;
}
return self;
}
- (void) release
{
if (sTier_count > 0) {
sTier_count--;
}
}
- (NSString*) description
{
return [NSString stringWithFormat:
@"i'm a tier, my number is %d", tier_num];
}
@end
@interface Engine : NSObject
@end
@implementation Engine
- (NSString*) description
{
return (@"i'm a engine");
}
@end
@interface Car : NSObject
{
Engine* engine;
Tier* tiers[4];
}
@end
@implementation Car
- (id) init
{
if (self = [super init]) {
engine = [Engine new];
int i = 0;
for (; i<4; i++) {
tiers[i] = [Tier new];
}
}
return self;
}
- (NSString*) description
{
return ("@I'm a car");
}
- (void) print
{
int i = 0;
for(; i<4; i++) {
NSLog(@"%@", tiers[i]);
}
NSLog(@"%@", engine);
}
@end
int main(char argc, char* argv[]) {
Car* car = [Car new];
[car print];
return 0;
}