Ivar显示为null,尽管它被强烈引用并初始化和分配

时间:2013-07-23 02:40:26

标签: ios cocos2d-iphone

我有一个名为A的类,其公共ivar称为NSMutableArray类型的行。我在init方法中分配并初始化ivar。另一方面,我有另一个名为B的类,它强烈引用类A类的ivar。我在类B的init方法中分配并初始化类A.我期望的是:

在类B分配并初始化类A作为其实例变量之后,类A的公共ivar不应为null。我得到了什么:

当我执行以下操作时,我发现A类变量的lines变量为null:

   myClassAVariable=[[ClassA alloc]init ];
   NSLog(@"The lines object is %@",[myClassAVariable lines]);

注意:我正在使用cocos2d。

编辑:

这是ClassA.h文件的一部分;

@interface ClassA : CCLayer 
{
    NSMutableArray *lines;
}
@property(strong,nonatomic)NSMutableArray *lines;

以下是ClassA的init方法的一部分:

if( (self=[super init]) ) {
   lines=[[NSMutableArray alloc] init];
}
return self;

以下是ClassB界面的一部分:

 @interface ClassB : CCLayer
 {
       DrawLayer *draw;
 }
 @property(strong,nonatomic)DrawLayer* draw;

最后,这是ClassB的初始化:

if( (self=[super init]) ) {
   draw=[[DrawLayer alloc] init];
        CCLOG(@"Lines object is %@",[draw lines]);//Shows "Lines object is (null)"
}
return self;             

1 个答案:

答案 0 :(得分:2)

如果lines只是一个ivar,那么在调用[[ClassA alloc]init ];时不会调用它的setter。我建议把它变成一个强大的财产:

ClassA.h:

@property(nonatomic,strong) NSMutableArray *lines;
ClassA初始化方法中的

//initiliaze lines:
self.lines = [[NSMutableArray alloc]init];