单例,NSTimer

单例:
#import "Teacher.h"
static id teacher1=nil;
@implementation Teacher
+(id)getInstance{//这里的id最好用Teacher *;
if (teacher1==nil) {
teacher1=[[self alloc]init];
}
return teacher1;
}
@end

全的单例
static ClassA *chassA=nil;
+(ClassA *)getClassA{
if(classA==nil){
classA=[[super allocWithZone:NULL]init];
}
return classA;
}
 
+(id)allocWithZone:(NSZone *)zone{
return [[self getClassA]retain];
}
-(id)copy{
return self;
}
-(id)retain{
return self;
}
-(NSUInteger)retainCount{
return NSUIntegerMax;
 
}
-(void)release{
//不做任何处理。
}
-(void)autorelease{
return self;
}
NSTimer:
#import "Dog.h"

@implementation Dog
@synthesize ID;
int i=3;
-(id)init{

self=[super init];
if (self) {
timer=[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(showTimer:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];

while (i>0) {
[[NSRunLoop currentRunLoop]runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0f]];
i--;
}

}
return self;
}
-(void)showTimer:(id)arg{
darkCount++;
NSLog(@"dog %d is calling %d",ID,darkCount);


}
@end

猜你喜欢

转载自zhangmingwei.iteye.com/blog/1877188