2011년 3월 28일 월요일

아이폰에서 Singleton 사용하기

출처 : http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html

//
// SynthesizeSingleton.h
// CocoaWithLove
//
// Created by Matt Gallagher on 20/10/08.
// Copyright 2009 Matt Gallagher. All rights reserved.
//
// Permission is given to use this source code file without charge in any
// project, commercial or otherwise, entirely at your risk, with the condition
// that any redistribution (in part or whole) of source code must retain
// this copyright and permission notice. Attribution in compiled projects is
// appreciated but not required.
//


SynthesizeSingleton.h


#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname) \
\
static classname *shared##classname = nil; \
\
+ (classname *)shared##classname \
{ \
        @synchronized(self) \
        { \
                if (shared##classname == nil) \
                { \
                        shared##classname = [[self alloc] init]; \
                } \
        } \
         \
        return shared##classname; \
} \
\
+ (id)allocWithZone:(NSZone *)zone \
{ \
        @synchronized(self) \
        { \
                if (shared##classname == nil) \
                { \
                        shared##classname = [super allocWithZone:zone]; \
                        return shared##classname; \
                } \
        } \
         \
        return nil; \
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
        return self; \
} \
\
- (id)retain \
{ \
        return self; \
} \
\
- (NSUInteger)retainCount \
{ \
        return NSUIntegerMax; \
} \
\
- (void)release \
{ \
} \
\
- (id)autorelease \
{ \
        return self; \
}



TestClient.h

#import <Foundation/Foundation.h>


@interface TestClass : NSObject {

}
+ (
TestClass *) sharedTestClass;
@end



TestClient.m


#import "TestClass.h"
#import “SynthesizeSingleton.h”



@implementation TestClass
SYNTHESIZE_SINGLETON_FOR_CLASS(
TestClass);

- (
id) init
{
        
if(self = [super init])
        {
        }
        
return self;
}
- (
void) dealloc
{
        [
super dealloc];
}
@end

댓글 없음:

댓글 쓰기