当前位置: 首页>编程语言>正文

The Objective-C Singleton

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

MySingleton.h:

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

MySingleton.m:

@implementation MySingleton
static MySingleton* _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 a singleton.");
_sharedMySingleton = [super alloc];
return _sharedMySingleton;
}
 
return nil;
}
 
-(id)init {
self = [super init];
if (self != nil) {
// initialize stuff here
}
 
return self;
}
 
-(void)sayHello {
NSLog(@"Hello World!");
}
@end

https://www.xamrdz.com/lan/5bs1967389.html

相关文章: