dispatch_once的意思是程序在执行期间只执行一次dispatch_once包含的代码:
建一单视图应用程序:‘
// TestClass.h
#import <Foundation/Foundation.h>
@interface TestClass : NSObject
- (void)test;
@end
// TestClass.m
#import "TestClass.h"
@implementation TestClass
- (void)test
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSLog(@"This is a test.");
});
}
@end
// ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
// ViewController.m
#import "ViewController.h"
#import "TestClass.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame:CGRectMake(20, 20, 280, 30)];
[button setTitle:@"Test" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)buttonClick:(id)seneder
{
TestClass *testObj = [[TestClass alloc] init];
[testObj test];
[testObj release];
}
@end
无论按钮按几次,This is a test. 只会打印一次