为什么NSMutableArray显示计数大小为0?

时间:2012-03-07 16:21:09

标签: objective-c ios

这里非常困惑......

我有一个名为“Section”的NSObject子类,其NSMutableArray属性称为“content”

 Section *sectionName = [[Section alloc] init];
 [[sectionName content] addObject:@"test"];
 [[sectionName content] addObject:@"test2"];
 [[sectionName content] addObject:@"test3"];

 NSLog(@"COUNT IS %i", [[sectionName content] count]);

为什么我的NSLOG显示“COUNT IS 0”??

3 个答案:

答案 0 :(得分:2)

您是否在content内初始化数组Section?你在做什么 - content = [[NSMutableArray alloc] init];

Lemme知道这是否有帮助。

答案 1 :(得分:2)

您是否正在初始化子类中的content?如果没有,那可能就是问题!

您的init方法应如下所示:

- (id)init
{
    if (self = [super init])
    {
      _content = [[NSMutableArray alloc] init];
    }
    return self;
}

如果你没有使用ARC,你的dealloc应该是这样的:

- (void)dealloc
{
  [_content release];
  [super dealloc];
}

答案 2 :(得分:1)

您可能需要分配NSMutableArray - 这通常是导致此问题的原因。

在Section.m中:

- (id) init {
    //...
    content = [[NSMutableArray alloc] init];
    //...
}