私のアプリケーションでは、いくつかのビューコントローラーに多くのビューコントローラーがあり、他のクラスで使用したいいくつかの変数があります。私の変数はアプリケーションデリゲートファイルに存在しないので、アプリケーションのどこでも使用できるようにグローバルにすることができますか?
2 に答える
            1        
        
		
私の意見では、シングルトンパターンを使用するのはどうですか? したがって、そのクラスの変数を使用する場合は、インスタンスを取得してから変数を使用します。
@interface MySingletonViewController : UIViewController
{
  //here your variables
  int globalVariables;
}
@property (nonatomic, assign) int globalVariables;
+ (MySingletonViewController *)sharedSingleton;
@end
@implementation MySingletonViewController
@synthesize globalVariables;
static MySingletonViewController *sharedSingleton = nil;
+ (MySingletonViewController *)sharedSingleton
{
  @synchronized(self)
  {
    if (sharedSingleton == nil)
      sharedSingleton = [[MySingleton alloc] init];
    return sharedSingleton;
  }
}
@end
UIViewController は実際にはクラスなので、この方法で実行できます:)これが役に立てば幸いです。
于 2012-10-16T07:54:18.397   に答える
    
    
            1        
        
		
確かにできますが、アプリ全体でグローバル変数を使用することは、間違いなくアーキテクチャ設計が壊れています。
CベースのObjective-Cとして、実装部分の外側の *.m ファイルで変数(この場合はクラスへのポインタ)を次のように定義できます。
MyVeryOwnClass *g_MyVeryOwnClassPointer = nil;
そして、次のようにアクセスします。
extern MyVeryOwnClass *g_MyVeryOwnClassPointer;
/* do some operations with your pointer here*/
または、extern 宣言をヘッダー ファイルに移動します。
PS: シングルトンを使用できます。それらは最良の解決策ではありませんが、生の変数を使用するよりも優れています。
于 2012-10-16T07:54:51.713   に答える