Objective-C:静态字段和实现单例模式 [英] Objective-C: static field and implementing singleton pattern

查看:79
本文介绍了Objective-C:静态字段和实现单例模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好,朋友.

再一次从新手那里得到关于Obj-C的愚蠢问题:)

Once again stupid question about Obj-C from newbie :)

我正在尝试在Obj-C中实现单例设计模式:

I'm trying to implement singleton design pattern in Obj-C:

@interface SampleSingleton : NSObject {
@private
    static SampleSingleton* instance;
}
+(SampleSingleton*) getInstance;

编译器返回错误:'static'之前的预期specifier-qualifier-list".

Compiler returns error: "expected specifier-qualifier-list before 'static'".

推荐答案

请在下面使用我正在使用的Objective-C代码段,以实现正确的线程安全的单例实现

Please find below the Objective-C code snippet I am using, for proper thread-safe singleton implementation

头文件:

/*
 *
 * Singleton interface that match Cocoa recommendation
 * @ http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW32
 * extended with thread-safe pattern
 */
@interface MyCustomManager : NSObject { 
}

#pragma mark Singleton Thred-Safe Pattern

+ (MyCustomManager *) sharedInstance;
+ (id)allocWithZone:(NSZone *)zone;
- (id)copyWithZone:(NSZone *)zone;
- (id)retain;
- (NSUInteger)retainCount;
- (void)release;
- (id)autorelease;

#pragma mark -

实施文件:

/*
 * My custom manager Class singleton implementation
 */
@implementation MyCustomManager

#pragma mark Initializers

/*
 * specific initialize goes here
 */
- (void) specificInitialize
{
    // ...
}

/*
 * Ensure any owned object is properly released
 */
- (void) dealloc
{
[super dealloc];
}

#pragma mark -

#pragma mark Singleton Thred-Safe Pattern

//- use Volatile to make sure we are not foiled by CPU caches
static void * volatile sharedInstance = nil;                                                

/*
 * retrieve sharedInstance based on OSAtomicCompareAndSwapPtrBarrier that 
 * acts as both a write barrier for the setting thread and a read barrier from the testing thread
 * more info @ http://stackoverflow.com/questions/145154/what-does-your-objective-c-singleton-look-like/2449664#2449664
 * and http://stackoverflow.com/questions/6915/thread-safe-lazy-contruction-of-a-singleton-in-c/6943#6943
 */
+ (MyCustomManager *) sharedInstance {  
    //- check sharedInstance existenz 
    while (!sharedInstance) {  
        //- create a temporary instance of the singleton    
        id temp = [super allocWithZone:NSDefaultMallocZone()];
        //- The OSAtomicCompareAndSwapPtrBarrier function provided on Mac OS X 
        //- checks whether sharedInstance is NULL and only actually sets it to temp to it if it is. 
        //- This uses hardware support to really, literally only perform the swap once and tell whether it happened.
        if(OSAtomicCompareAndSwapPtrBarrier(0x0, (void *)temp, &sharedInstance)) {
            //- compute singleton initialize
        MyCustomManager *singleton = (MyCustomManager *) sharedInstance;
            [singleton specificInitialize];
        }
        else {
            //- if the swap didn't take place, delete the temporary instance
            [temp release]; 
            temp = nil;
        }                                                                                                 
    }   
    //- return computed sharedInstance
    return sharedInstance;                                                                        
}

/*
 * method to ensure that another instance is not allocated if someone tries to allocate 
 * and initialize an instance of your class directly instead of using the class factory method. 
 * Instead, it just returns the shared object.
 */
+ (id)allocWithZone:(NSZone *)zone
{
    return [[self sharedInstance] retain];
}

/*
 * Implements the base protocol methods to do the appropriate things to ensure singleton     status. 
 * Applies to memory-managed code, not to garbage-collected code
 */
- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

/*
 * Implements the base protocol methods to do the appropriate things to ensure singleton status. 
 * Applies to memory-managed code, not to garbage-collected code
 */
- (id)retain
{
    return self;
}

/*
 * Implements the base protocol methods to do the appropriate things to ensure singleton status. 
 * Applies to memory-managed code, not to garbage-collected code
 */
- (NSUInteger)retainCount
{
    return NSUIntegerMax;  //denotes an object that cannot be released
}

/*
 * Implements the base protocol methods to do the appropriate things to ensure singleton status. 
 * Applies to memory-managed code, not to garbage-collected code
 */
- (void)release
{
    //do nothing
}

/*
 * Implements the base protocol methods to do the appropriate things to ensure singleton status. 
 * Applies to memory-managed code, not to garbage-collected code
 */
- (id)autorelease
{
    return self;
}

#pragma mark -

只是为了帮助您从Objective-C入手,而不会迷失在项目结构中,您可以考虑使项目结构与文件系统相匹配,这样,随着您的项目变大,您就不会迷路.

Just to help you starting in objective-c and not get lost in your project structure, you can consider having the project structure matching your file system so as your project becomes bigger you won't get lost.

也请考虑使用适当的类命名约定,并遵守该约定.

Also please consider using a proper class naming convention, and stick to it.

我为您提供了我的样品:

I a providing you mine as sample:

  • 任何与单例模式匹配的类都使用Manager后缀(例如MyCustomManager)命名.

任何静态类都使用Helper后缀(例如MyCustomHelper)命名.

Any static class is named using Helper suffix (E.g. MyCustomHelper).

任何专用于控制特定过程的类都使用控制器后缀(例如MyParticularTaskConstroller)命名.


Any class dedicated to control particular process is named using Controller suffix ( E.g. MyParticularTaskConstroller ).


任何从另一个控件继承的UI控件都需要提供后缀(例如,从UITableViewCell继承的MyCustomDetailCell)

Any UI control that inherit from another control needs provide control suffix ( E.g. MyCustomDetailCell inheriting from UITableViewCell )

希望这会有所帮助.

这篇关于Objective-C:静态字段和实现单例模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆