正如Richard指出的那样,缺少大括号将var定义为全局变量。在声明实例变量方面,有几种方法:
在Objective-C Programming Language中讨论了在@interface
或@implementation
中声明实例变量。
所以,你可以在@interface
,这是你在历史上将会看到的实例变量定义的最常见的地方定义一个实例变量x
:
@interface TestClass : NSObject
{
NSInteger x;
}
@end
@implementation TestClass
// define the methods
@end
正如上面的链接描述,但是,你也可以在@implementation
定义它(虽然,因为习惯问题,我不认为你会看到这个非常频繁):
@interface TestClass : NSObject
@end
@implementation TestClass
{
NSInteger x;
}
// define the methods
@end
其实是有,你可以把你的实例变量一个第三名,在课程扩展中(稍后在same document中讨论)。在实践中,这意味着你可以有你的.h定义如下
// TestClass.h
@interface TestClass : NSObject
// define public properties and methods here
@end
和您的m如下:
// TestClass.m
// this is the class extension
@interface TestClass()
{
NSInteger x;
}
@end
// this is the implementation
@implementation TestClass
// define the methods
@end
这最后一种方法(与@interface
一.H,用类.M扩展名和@implementation
)现在是Xcode模板在创建新类时使用的格式。实际上,这意味着您可以将公共声明放在.h文件中,并将您的私有@property
和实例变量放入类扩展中。它只是让你的代码更清洁一些,使你不需要使用私有实现细节来混淆你的.h文件(这实际上就是你的类的公共接口)。例如变量,或许在@implementation
中定义实例变量的先前技术是等价的,但我认为它不适用于@property
声明,在这种情况下,类扩展会变得有用。
来源
2012-08-12 07:23:43
Rob
Objective-C没有成员变量;它有实例变量。或多或少都是一样的,但命名的一致性有所帮助。 – bbum 2012-08-12 06:05:52