简体   繁体   English

目标C:NSMutableArray不保留对象

[英]Objective C: NSMutableArray does not retain objects

I'm so stumped by this, I set the object in the array, but when I check it after they're all set, it comes up as (null) 我对此感到困惑,我在数组中设置了对象,但是当我们将它们全部设置后进行检查时,它会显示为(null)

for (int i = 0; i < [lines count]; i+=2) {
    [terms addObject:[lines objectAtIndex:i]];
    NSLog(@"%@",[terms objectAtIndex:i]);
}

Am I doing something wrong? 难道我做错了什么? terms is declared in the header, set as a property, and synthesized as an NSMutableArray terms在标题中声明,设置为属性,并合成为NSMutableArray

You have to first alloc and init the array before you use it. 在使用之前,必须首先分配并初始化数组。 Setting the property makes it accessible outside the class and the synthesizer sets up the getter and setter but it doesn't alloc and init it. 设置属性使其可以在类外部访问,合成器设置getter和setter但它不分配和初始化它。

NSMutableArray* terms = [[NSMutableArray alloc] init];

"Synthesized as a NSMutableArray" - that's weird wording. “合成为NSMutableArray” - 这是一个奇怪的措辞。 In ObjC, @synthesize does not initialize variables - just generates a getter and a setter method. 在ObjC, @synthesize不初始化变量-只产生一个getter和setter方法。 You still have to allocate the variable somehow - either by assigning to a property, or by setting the corresponding ivar directly. 您仍然必须以某种方式分配变量 - 通过分配属性或直接设置相应的ivar。 init is a nice place to do that. init是一个很好的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM