gpt4 book ai didi

Objective-C:静态字段和实现单例模式

转载 作者:行者123 更新时间:2023-12-04 02:54:03 25 4
gpt4 key购买 nike

美好的一天, friend 们。

再一次来自新手关于 Obj-C 的愚蠢问题 :)

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

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

编译器返回错误:“在‘static’之前需要说明符限定符列表”。

最佳答案

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

头文件:

/*
*
* 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 开始,而不是迷失在您的项目结构中,您可以考虑让项目结构与您的文件系统相匹配,这样当您的项目变大时您就不会迷失方向。

另外请考虑使用适当的类命名约定,并坚持使用。

我向您提供我的 sample :

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

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

  • 任何专用于控制特定进程的类都使用 Controller 后缀命名 (例如 MyParticularTaskConstroller)

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

希望这对您有所帮助。

关于Objective-C:静态字段和实现单例模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6912703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com