- //Singleton类声明
- #import <Foundation/Foundation.h>
- @interface Singleton :NSObject
- +(Singleton*)GetInstance;
- -(void)SayHello;
- @end
- //Singleton类实现
- #import "Singleton.h"
- @implementation Singleton
- static Singleton *myInstance =nil;
- +(Singleton*)GetInstance{
- @synchronized([Singleton class]){
- if(myInstance ==nil){
- myInstance = [[self alloc]init];
- }
- }
- return myInstance;
- }
- +(id)alloc{
- @synchronized([Singleton class]){
- if (myInstance ==nil) {
- myInstance = [super alloc];
- return myInstance;
- }
- }
- return nil;
- }
- -(id)init{
- self = [super init];
- if(self !=nil){
- NSLog(@"初始化数据");
- }
- return self;
- }
- -(void)SayHello{
- NSLog(@"Hello,world!");
- }
- @end
- //================================================
- Main方法调用
- #import <Foundation/Foundation.h>
- #import "Singleton.h"
- int main (int argc,const char * argv[])
- {
- @autoreleasepool{
- Singleton *singleton = [Singleton GetInstance];
- [singleton SayHello];
- singleton = [Singleton new];
- [singleton SayHello];
- }
- return 0;
- }
- 原文链接:http://blog.csdn.net/lanergaming/article/details/7597267
objective-c单例类实现
最新推荐文章于 2023-09-14 19:23:51 发布