0

让我们想象一下这种情况:

游戏.h:

@interface Game : CCLayer
{    
    NSMutableArray* questions;
}

@property (nonatomic,retain) NSMutableArray* questions;


- (void) didLoadFromCCB;
- (void) pressitem:(id)sender;

@end

游戏.m

 @implementation Game

 @synthesize questions;

 - (void) didLoadFromCCB
 {
     NSMutableArray *questions = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithInteger:-1],nil];

     NSLog(@"didload %@", questions);
 }


 - (void) pressitem:(id)sender
 {
     NSLog(@"pressitem %@",questions);
 }
@end

我从 didLoadFromCCB 获取日志,但在 pressitem 上它返回 null。不应该通过我的所有实现来访问数组吗?

我知道这个接缝就像一个真正的菜鸟问题,但我来自 actionscript/php 背景,我刚刚订购了一本 C 和一本 Objective C 的书,但在我等待的时候,我只是想深入研究一下。

感谢您的时间 :)

4

2 回答 2

2

questions您在didLoadFromCCB阴影中的本地声明会影响实例变量。你可能应该只写那一行:

self.questions = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithInteger:-1],nil];

然后,您将创建数组并将指向它的指针存储在实例变量中,而不仅仅是创建一个立即超出范围的本地指针。

于 2013-02-27T22:28:22.693 回答
0

范围。NSMutableArray *questions声明方法的局部变量- didLoadFromCCB。它不设置实例变量(具有较小范围的变量会抑制具有相同名称但范围较宽的变量)。简单地写

self.questions = [[NSMutableArray alloc] initWithObject:[NSNumber numberWithInteger:-1]];

反而。

于 2013-02-27T22:29:13.017 回答