0

在我的应用程序中,一些视图控制器中有很多视图控制器,一些变量是我想在其他类中使用的。我的变量不存在于应用程序委托文件中,所以我可以让它全局使用我的应用程序中的每个地方吗?

4

2 回答 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 回答