本文介绍了客观c中的单身人士的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看到了一个关于客观C书的单例例子。然而,我不知道目标c和其他lang之间的'单身'定义的含义是否存在差异。可以使用[[SingletonClass alloc] init]来创建新对象吗?如果是,如何保证内存中只有一个对象?
I saw a singleton example on objective-c book. However, I don't know if there is difference of meaning of 'singleton' definition between objective-c and other langs. Can this [[SingletonClass alloc] init] still be used to create a new object? If yes, how to guarantee there is only one object in the memory?
#import "SingletonClass.h"
@implementation SingletonClass
static SingletonClass *sharedInstance = nil;
// Get the shared instance and create it if necessary.
+ (SingletonClass*)sharedInstance {
if (sharedInstance == nil) {
sharedInstance = [[super allocWithZone:NULL] init];
}
return sharedInstance;
}
// We can still have a regular init method, that will get called the first time the Singleton is used.
- (id)init
{
self = [super init];
if (self) {
// Work your initialising magic here as you normally would
}
return self;
}
推荐答案
Colin Wheeler 。
Colin Wheeler has a post on Singletons in Cocoa.
我同意Colin关于Singleton的不合需要。
I agree with Colin about the undesirability of Singletons.
这篇关于客观c中的单身人士的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!