为什么这些“成员”变量表现得像静态?

时间:2012-08-12 00:41:51

标签: iphone objective-c ios pointers

我有MyUnitClass的实现声明如下:

@implementation MyUnitClass
Unit* _unit = NULL;

在for循环中,我迭代了很多次并创建了MyUnitClass的多个实例。 Unit表现得像一个静态变量。我在MyUnitClass的init方法中设置了一个断点,这是我每次上课时得到的:

(gdb) print _unit
$4 = (Unit *) 0x112340
(gdb) print _unit
$5 = (Unit *) 0x112340

注意:

我已经通过将变量移入@interface声明来解决了这个问题。如果您回答这个问题,那么查看指向可以找到此信息的页面的链接会很棒。

2 个答案:

答案 0 :(得分:8)

这是因为你没有用花括号包围变量,使它成为全局变量。要修复,请尝试像这样定义:

@implementation MyObject {
   unsigned int myVar;
}

// rest of implementation

@end

只能有一个@implementation块,所以如果它已经在.h文件中声明,那么需要在那里添加成员,或者需要将整个块移动到.m文件中。

这是来自C的遗留物,编译器并不完全知道你希望它是iVar,而不是全局。

答案 1 :(得分:3)

正如理查德指出的那样,没有括号将var定义为全局。在声明实例变量方面,有几种方法:

Objective-C Programming Language中讨论了@interface@implementation中的实例变量声明。

因此,您可以在x中定义一个实例变量@interface,这是您在历史上最常见的实例变量定义位置:

@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声明,在这种情况下类扩展变得有用。

相关问题