Created
August 18, 2012 06:56
-
-
Save darcyliu/3384993 to your computer and use it in GitHub Desktop.
Objective-C Singleton Demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
#import "Singleton.h" | |
int main(int argc, const char * argv[]) | |
{ | |
@autoreleasepool { | |
NSLog(@"Objective-C Singleton Demo"); | |
[[Singleton sharedSingleton] sayHello]; | |
[[Singleton sharedSingleton] sayHello]; | |
} | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface Singleton : NSObject | |
+(Singleton*)sharedSingleton; | |
-(void)sayHello; | |
@end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "Singleton.h" | |
@implementation Singleton | |
static Singleton* _sharedSingleton = nil; | |
+(Singleton *) sharedSingleton{ | |
@synchronized([Singleton class]) | |
{ | |
if (!_sharedSingleton) | |
[[self alloc] init]; | |
return _sharedSingleton; | |
} | |
return nil; | |
} | |
+(id)alloc | |
{ | |
@synchronized([Singleton class]) | |
{ | |
NSAssert(_sharedSingleton == nil, @"Attempted to allocate a second instance of a singleton."); | |
_sharedSingleton = [super alloc]; | |
return _sharedSingleton; | |
} | |
return nil; | |
} | |
-(id)init { | |
self = [super init]; | |
if (self != nil) { | |
// initialize stuff here | |
} | |
return self; | |
} | |
-(void)sayHello { | |
NSLog(@"Hello World!"); | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment