单例设计 [英] Singleton Design
问题描述
我正在创建一个使用卡片的游戏。
我有一个AppController类,在nib中有一个实例。
AppController实例有一个名为wordList的NSArray实例变量。
在init上,nib的AppController实例生成一个新的GameCard。
每个gamecard都有一个包含从AppController列表中随机选择的5个词的字词数组。
因为列表很大,我想把它读入内存只有一次。因此,我只需要一个AppController的实例,作为一个singleton类。每次从AppController中创建一个新的GameCard时,它应该访问同一单例实例来检索wordlist。
所以基本上,我需要一个单独的AppController创建GameCards,每个GameCard都有一个对原来的AppController的引用。
我不知道如何实现这个。
I'm creating a game that uses cards. I have an AppController class with one instance in the nib. The AppController instance has an NSArray instance variable called wordList. On init, the nib's instance of AppController generates a new GameCard. Every gamecard has an array of words containing 5 words selected at random from the the list in AppController. Because the list is large, I'd like to read it into memory only once. Therefore, I want only one instance of AppController, as a singleton class. Every time a new GameCard is created from within AppController, it should access that same singleton instance to retrieve the wordlist. So basically, I need a singleton AppController that creates GameCards, where each GameCard has a reference to the original AppController. I'm not sure how to implement this. Sorry if the explanation was confusing.
我在网上找到的代码示例如下( http://numbergrinder.com/node/29 )
A code example I found online follows (http://numbergrinder.com/node/29)
+ (AppController *)instance
{
static AppController *instance;
@synchronized(self) {
if(!instance) {
instance = [[AppController alloc] init];
}
}
return instance;
}
但是当我试图通过代码在GameCard实例中做一些事情下面,我的应用程序永远启动,Xcode告诉我它正在加载99797堆栈帧。
But when I tried to do something with it in a GameCard instance through the code below, my application took forever to launch and Xcode told me it was loading 99797 stack frames.
AppController *controller = [AppController instance];
推荐答案
这听起来像一个无限循环。请确保 - [AppController init]没有调用+ [AppController实例]。
It sounds like an infinite loop. Make sure that -[AppController init] isn't calling +[AppController instance].
这篇关于单例设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!