模拟静态变量及静态类继承
在Objective-C中是没有静态类变量一说的,不过我们可以模拟出来,但如果类对象之间还有继承关系,这样就一点复杂的了。我们这里假设一个Coupon类对象需要保存当前还剩多少有优惠券,还有一个继承于Coupon类对象的NewCoupon类对象,但它也保存有自已可用的优惠券的数量,我们如何保证他们的静态类变量相互独立,请看下面的例子。
Coupon.h
#import <Foundation/Foundation.h>
@interface Coupon : NSObject {
}
+(int) numberCouponsLeft;
+(void) resetCoupon;
@end
Coupon.m
#import "Coupon.h"
#define INITIAL_COUPON_ALLOCATION 100
//设置静态变量
static int availableCoupons = INITIAL_COUPON_ALLOCATION;
//在实现类中定义私有静态访问器
@interface Coupon()
+(int) availableCoupons;
+(void) setAvailableCoupons:(int) inAvailableCoupons;
@end
@implementation Coupon
+(int) availableCoupons
{
return availableCoupons;
}
+(void)setAvailableCoupons:(int)inAvailableCoupons
{
availableCoupons = inAvailableCoupons;
}
//为了支持静态类的继承,重点看init
-(id) init
{
if((self = [super init]))
{
//[self class] 表示用作接收者的那个对象,如果是继承类,指的是该继承类对象。
if([[self class] availableCoupons] == 0)
{
//如果有效的Coupon为0,则消毁该类对象
[self release];
return nil;
}
//当前有效的Coupon减1
[[self class] setAvailableCoupons: [[self class] availableCoupons]-1];
}
return self;
}
+(int) numberCouponsLeft
{
return [self availableCoupons];
}
+(void) resetCoupon
{
[self setAvailableCoupons:INITIAL_COUPON_ALLOCATION];
}
@end
NewCoupon.h
#import <Foundation/Foundation.h>
#import "Coupon.h"
@interface NewCoupon : Coupon {
}
@end
NewCoupon.m
#import "NewCoupon.h"
#define INITIAL_New_COUPON_ALLOCATION 200
//在继承类中设置新的静态变量
static int availableCoupons = INITIAL_New_COUPON_ALLOCATION;
@interface NewCoupon()
+(int)availableCoupons;
+(void) setAvailableCoupons: (int)inAvailableCoupons;
@end
@implementation NewCoupon
+(int)availableCoupons
{
return availableCoupons;
}
+(void) setAvailableCoupons:(int)inAvailableCoupons
{
availableCoupons = inAvailableCoupons;
}
+(void) resetCoupon
{
[self setAvailableCoupons:INITIAL_New_COUPON_ALLOCATION];
}
@end
main.m
#import <Foundation/Foundation.h>
#import "Coupon.h"
#import "NewCoupon.h"
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// insert code here...
//NSLog(@"Hello, World!");
[[Coupon alloc] init];
NSLog(@"%d", [Coupon numberCouponsLeft]);
[Coupon resetCoupon];
NSLog(@"%d", [Coupon numberCouponsLeft]);
[[NewCoupon alloc] init];
NSLog(@"%d", [NewCoupon numberCouponsLeft]);
[NewCoupon resetCoupon];
NSLog(@"%d", [NewCoupon numberCouponsLeft]);
[pool drain];
return 0;
}
返回结果:
[Switching to process 3200 thread 0x0]
2011-05-03 10:15:08.505 demo04[3200:903] 99
2011-05-03 10:15:08.508 demo04[3200:903] 100
2011-05-03 10:15:08.508 demo04[3200:903] 199
2011-05-03 10:15:08.509 demo04[3200:903] 200