objective-c単例クラス実装

1493 ワード

//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;
    
}