1

私の頭に浮かぶ最初のアプローチは、シングルトン オブジェクトを appDelegate オブジェクトにプロパティとして配置することです。このようにして、どこからでもアクセスできます

#import "myAppDelegate.h"
// ...
[[(myAppDelegate *)[UIApplication sharedApplication] delegate] SingletonObj]

欠点は、SingletonObj が実際にはデリゲートのプロパティであることを使用しているクラスに伝えるために、デリゲートのヘッダーを明示的にキャストおよびインポートする必要があることです。そして、これによりコードが少し臭くなると思います。

2 番目のアプローチは、正規のシングルトン クラスを作成することです。ただし、これにはさらに作業が必要です。個人的には、1 つの Singleton クラスで十分だと思います。

私はプログラマーではないので、私の推論の修正と、この件に関する意見をいただければ幸いです。

4

3 に答える 3

5

Singletons are most often handled in a class via a method like +sharedInstance.

Here is a good write-up.

于 2010-09-28T18:16:04.900 に答える
1

ネット上でシングルトンを簡単に生成するためのxcodeテンプレートを見つけました。

于 2010-10-12T13:30:38.170 に答える
0

Best practice is to only ever put UIApplicationDelegate-related things in your AppDelegate class. Evarr.

Decide if you really need a singleton. If you do, just make a legit singleton class. It will be easier in the long run; did you notice how long it took to type that monster of a line, where you tried to get the singleton object out of the AppDelegate? Agh.

(Also, just a little bit of idiom: classes start with a capital letter, and methods start with a lowercase letter; hence, you problem meant [[(MyAppDelegate *)[UIApplication sharedApplication] delegate] singletonObj].)

于 2010-09-28T18:18:44.150 に答える