iOS的单例:
//Singleton.h
@interface Singleton : NSObject
+ (Singleton *) instance;
@property (nonatomic,strong) NSString *singletonData;
@end
//Singleton.m
#import "Singleton.h"
@implementation Singleton
@synthesize singletonData = _singletonData;
static Singleton *instance =nil;
+ (Singleton *) instance{
static dispatch_once_t once;
dispatch_once(&once,^{
instance = [[self alloc] init];
});
return instance;
}
其中 static Singleton instance
为静态变量 ,类方法为 + (Singleton ) instance
instance 方法采用了 GCD(Grand Central Dispatch)技术,这是一种基于C语言的多线程访问技术,在上述代码中dispatch_once函数就是由GCD提供的.它只执行一次,
stringByAddingPercentEscapesUsingEncoding
转换为 url编码.
delegate:
首先声明一个如下.h文件:
@protocol PhilosopherDelegate <nsobject>
@required
-(void) sleep;
-(void) eat;
-(void) work;
@end
然后声明两个 相互依赖的.h.m
#import "PhilosopherDelegate.h"
@interface Philosopher : NSObject
{
NSTimer *timer;
int count;
}
@property (nonatomic,weak) id<philosopherDelegate> delegate;
-(void) start;
-(void) handle;
@end
#import "Philosopher.h"
@implementation Philosopher
@synthesize delegate;
-(void) start{
count =0;
timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(handle) userInfo:nil repeats:YES];
}
-(void)handle{
switch (count) {
case 0:
[self.delegate sleep];
count++;
break;
case 1:
[self.delegate eat];
count++;
break;
case 2:
[self.delegate work];
[timer invalidate];
break;
}
}
@end
然后再ViewController
中import,初始化上面相互依赖的.h文件
代码如下:
#import "ViewController.h"
#import "Philosopher.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Philosopher *obj = [[Philosopher alloc]init];
obj.delegate = self;
[obj start];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void) sleep{
NSLog(@"sleep");
}
-(void) eat{
NSLog(@"eat");
}
-(void) work{
NSLog(@"work");
}
@end
© 著作权归作者所有
文章评论(0)