属性变量无法读取?

时间:2011-11-05 16:58:39

标签: objective-c cocos2d-iphone

在标题中,我声明了我的

NSString *name;

变量。然后我用

创建一个属性
@property (nonatomic,retain) NSString *name;

我在实现中综合了它

@synthesize name;

并且,立即在init方法中给它一个值:

name = @"HELLO";

后来我在场景中添加了一个孩子。稍后,这个孩子将尝试访问此属性。它就像

Battle *battleScene = (Battle*)self.parent;
NSLog(@"%@",battleScene.name);

但我得到“null”。那是为什么?

3 个答案:

答案 0 :(得分:1)

Battle 类是否定义name?另外,您是否在设置 battleScene 之前或之后创建了name = @"HELLO";的实例?

例如

@interface Battle : NSObject
{
    NSString *name;
}
@property (nonatomic,retain) NSString *name;
@end

答案 1 :(得分:1)

其中一个原因可能是self.parent为零。如果您尝试在子节点的init方法中运行代码,则会发生这种情况。

CCNode* child = [[[CCNode alloc] init] autorelease];
// at this point the init method is run but parent of the child is still nil …
…

[self addChild:child];
// now the parent of the child is set, after it's been added to the hierarchy

如果您在init方法中运行此操作,请将该代码移至onEnter方法:

-(id) init
{
     // self.parent == nil !!
} 

-(void) onEnter
{
    // self.parent is guaranteed to be non-nil in onEnter
    Battle *battleScene = (Battle*)self.parent;
    NSLog(@"%@",battleScene.name);
}

答案 2 :(得分:-1)

name = @"HELLO"; 

未设置属性。

self.name = [NSString stringWithString:@"HELLO"]; 

将为您设置属性。它将为您保留对象,这是分配它的好方法,因为[NSString stringWithString:@"HELLO"]是自动释放的。使用self.name =将释放您之前的名称并保留您正在设置的名称。

通过在属性声明中包含retain来获得此行为