개발/개발 자료
(아이폰) 싱글톤 전역변수 사용방법
시원한물냉
2014. 1. 29. 15:05
h file...
@interface GlobalTest : NSObject {
NSString *msg;
}
+ (GlobalTest *)sharedSingleton;
m file...
@implementation Conf
static GlobalTest * _globalTest = nil;
- (id) init {
msg = @"Globall Value Test";
}
+(GlobalTest *)sharedSingleton
{
@synchronized([GlobalTest class])
{
if (!_globalTest)
[[self alloc] init];
return _globalTest;
}
return nil;
}
+(id)alloc
{
@synchronized([GlobalTest class])
{
NSAssert(_globalTest == nil, @"Attempted to allocate a second instance of a singleton.");
_globalTest = [super alloc];
return _globalTest;
}
return nil;
}
@interface GlobalTest : NSObject {
NSString *msg;
}
+ (GlobalTest *)sharedSingleton;
m file...
@implementation Conf
static GlobalTest * _globalTest = nil;
- (id) init {
msg = @"Globall Value Test";
}
+(GlobalTest *)sharedSingleton
{
@synchronized([GlobalTest class])
{
if (!_globalTest)
[[self alloc] init];
return _globalTest;
}
return nil;
}
+(id)alloc
{
@synchronized([GlobalTest class])
{
NSAssert(_globalTest == nil, @"Attempted to allocate a second instance of a singleton.");
_globalTest = [super alloc];
return _globalTest;
}
return nil;
}
호출시
#import "GlobalTest.h"
NSLog([[GlobalTest sharedSingleton] msg]);
#import "GlobalTest.h"
NSLog([[GlobalTest sharedSingleton] msg]);
변수에 값을 대입하고 싶으면 프로퍼티 선언 후
[[GlobalTest sharedSingleton] setMsg:@"text"];
[[GlobalTest sharedSingleton] setMsg:@"text"];
[출처] 전역변수 사용법 - 싱글톤|작성자 doghole