无法在@interface或@protocol中声明变量 [英] Cannot declare variable inside @interface or @protocol
问题描述
我从一开始就构建了一个iOS应用,其中包含错误。由于源是从模板开始构建的,因此其appdelegate.h看起来像:
I have an iOS app built since the beginning with an error in it. Since the source was began constructed from the template, its appdelegate.h looks like:
@interface myAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
myViewController *viewController;
}
BOOL myBool; // intended to be globally accessible
NSString *myString; // intended to be globally accessible
@end
我指的是<来自许多其他.m源文件的strong> myBool 和 * myString ,以及全局变量。
I refer to myBool and *myString from many other .m source files, as to global variables.
XCode 3.2.6以下,我不记得在编译时遇到任何问题。
Below XCode 3.2.6, I can not remember getting any issues at compile time.
3.2.6时,在appdelegate.h中指向这些全局变量的编译时出现警告,说: 无法在@interface或@protocol中声明变量。由于编译或应用程序运行时没有其他问题,遗憾的是我没有考虑这些警告。
At 3.2.6, warning appeared at compile pointing to these "global" variables in appdelegate.h, saying: "Cannot declare variable inside @interface or @protocol". As there were no further problems with compilation or during app runtime, unfortunately I did not consider these warnings.
现在,使用XCode 4.2,我无法编译此源代码,因为前面的警告变成了构建错误。它们引用并指向不同.m文件中的每一行,其中存在对全局变量的引用。
Now, using XCode 4.2, I am unable to compile this source, because the former warnings turned into build errors. They refer and point to each of those lines in the different .m files where there is a reference to the "global variables".
是否有一种简单的方法可以解决这个问题问题,考虑到我仍然想要将这些变量/引用作为全局变量/参考?
Is there an easy way to correct this problem, considering that I still want to access these variables/references as global ones?
其他问题:我正在评估到目前为止收到的答案(感谢大家),另一个问题:任何想法为什么在XCode v3.2.6下面没有给出警告,只有3.2.6中的警告如果这是我身边的真实错误?为什么代码仍然编译并且可以毫无问题地运行?
Additional question: while I am evaluating so far received answers (thanks for all of you), another question: any idea why no warning were given below XCode v3.2.6, and only warnings in 3.2.6 if this is a real error from my side? And why the code was still compiled and could be run without any problem?
推荐答案
他们不能去那里。你可以将它们放在花括号{}中:
They can't go there. You can put them inside the curly braces {} like this:
@interface myAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
myViewController *viewController;
BOOL myBool; // intended to be globally accessible
NSString *myString; // intended to be globally accessible
}
@end
这使它们成为实现类的全局。但是如果你想让它们全局到你应用程序中的每个类,那么你应该将它们放在你的App-Prefix.pch文件中:
And that makes them global to the implementation class. But if you want them global to every class in your app then you should drop them in your App-Prefix.pch file:
//
// Prefix header for all source files of the ... project
//
#import <Availability.h>
BOOL myBool; // intended to be globally accessible
NSString *myString; // intended to be globally accessible
#ifndef __IPHONE_3_0
这篇关于无法在@interface或@protocol中声明变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!