The Objective-C Singleton

-- iOS (iPhone) 2014. 8. 13. 06:52
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Below is a template for the singletons that we use in objective-c.



MySingleton.h:


#import <Foundation/Foundation.h>
 
@interfaceMySingleton :NSObject {
 
}
+(MySingleton*)sharedMySingleton;
-(void)sayHello;
@end



MySingleton.m:


@implementationMySingleton
staticMySingleton*_sharedMySingleton = nil;
 
+(MySingleton*)sharedMySingleton
{
        
@synchronized([MySingleton class])
        
{
                
if (!_sharedMySingleton)
                        
[[self alloc] init];
 
                
return_sharedMySingleton;
        
}
 
        
return nil;
}
 
+(id)alloc
{
        
@synchronized([MySingleton class])
        
{
                NSAssert
(_sharedMySingleton == nil, @"Attempted to allocate a second instance of asingleton.");
                _sharedMySingleton
= [super alloc];
                
return_sharedMySingleton;
        
}
 
        
return nil;
}
 
-(id)init {
        self
= [super init];
        
if (self != nil) {
                
// initialize stuff here
        
}
 
        
return self;
}
 
-(void)sayHello {
        NSLog
(@"HelloWorld!");
}
@end



Using themethods of the singleton is then as easy as this:


[[MySingletonsharedMySingleton] sayHello];



출처 : http://getsetgames.com/2009/08/30/the-objective-c-singleton/


posted by 어린왕자악꿍