在Objective-C中声明全局变量的正确方法是什么?



所以,我想知道在iOS项目中声明全局变量的正确方法是什么。我不想把它设置为一个属性,因为这个变量不应该从类外访问。

我将提供我所看到的几种方法,让我知道哪一种方法是正确的,如果有另一种方法更好。

这样,我在实现文件.m中的@interface声明后的花括号内添加了全局变量。然后我可以在viewDidLoad

中初始化变量
#import "ViewController.h"
@interface ViewController () {
    int globalVariableTest;
}
@end
@implementation ViewController

另一种方法是在实现文件.m中的@implementation声明之后将全局变量添加到花括号内。再次在viewDidLoad

中进行初始化
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController {
       int globalVariableTest;
}

另一种方法是在没有花括号的@implementation之后添加变量,这也允许我设置没有viewDidLoad的初始值

#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
int globalVariableTest = 1;

另一种方法是在头文件.h

@interface之后添加变量
@interface ViewController : UIViewController
{
    int globalVariableTest;
}

所以如果有更好的方法请让我知道,所有的帮助将不胜感激!

在花括号内声明变量实际上是声明一个实例变量或简称为"ivar"。也就是说,对于类的实例来说,它是一个局部变量。

这在过去只在@interface声明之后才有可能,这就是为什么你有时会在那里看到它。这在Xcode 4左右改变了,所以你现在也可以在@implementation之后这样做。据我所知,这只是一种风格偏好。在类之外永远不能访问变量(理论上)。从技术上讲,C)中的所有内容都可以访问所有内容,因此在。h中定义它们不会使它们公开。但是,它确实暴露了实现细节,这就是为什么我现在看到的大多数使用它们的代码都将它们放在@implementation中。

但是我不再在代码中看到它们了。因为当你定义一个@property的时候在幕后实际发生的是一个ivar,一个getter方法和一个setter方法实际上都是为你合成的。getter和setter方法分别只获取ivar的值和设置ivar的值。

因此,如果你想要的是与属性具有相同作用域的东西,但没有-myVar-setMyVar:方法,那么这是正确的方法。

但是你可能不希望那样。只有通过访问器方法才能访问ivars,这有很多原因。它允许您重写功能,转换值,以及抽象提供给您的所有其他有趣的事情。

如果你想要的是一个不能在类外访问的@property,只需在类扩展中声明它:

//In MyClass.m
@interface MyClass()
  @property NSNumber *myProperty;
@end
@implementation MyClass
  //All your implementation stuff here.
@end

因为它不在。h文件中,所以它对其他类不"可见"(理论上。

另一方面,如果你真正想要的是真正全局的东西(提示:你不应该这样做)。全局变量通常是一种糟糕的设计),您需要在任何@interface@implementation块之外的文件顶部定义它。

另一个相关的花边新闻:要定义一个作用域限制在给定文件的"全局"变量,请查看C语言的static关键字。很有趣。

你可以使用一个单例类在不同的类(视图控制器)中创建/共享(读/写)所有变量。

. h

@interface SharedVariables : NSObject  {
    NSDictionary *dicti_StackSites;
    NSDictionary *dicti_UserMe;
}
@property(nonatomic, strong) NSDictionary *dicti_StackSites;
@property(nonatomic, strong) NSDictionary *dicti_UserMe;
+(id)sharedVariablesManager;
@end

SharedVariables.m

#import "SharedVariables.h"
@implementation SharedVariables
@synthesize dicti_StackSites;
@synthesize dicti_UserMe;
+(id)sharedVariablesManager {
    static SharedVariables *sharedVariablesClass = nil;
    @synchronized(self) {
        if (sharedVariablesClass == nil) {
            sharedVariablesClass = [[self alloc] init];
        }
    }
    return sharedVariablesClass;
}
-(id)init {
    if (self = [super init]) {
        dicti_StackSites = [[NSDictionary alloc] init];
        dicti_UserMe = [[NSDictionary alloc] init];
    }
    return self;
}
-(void)dealloc {
}
@end

从任何其他类使用

#import "SharedVariables.h"
SharedVariables *sharedManager = [SharedVariables sharedVariablesManager];
//to get sharedManager.dicti_StackSites
//to set sharedManager.dicti_StackSites = ...

相关内容

最新更新