为什么我不能在不使用self的情况下初始化我的变量

Ell*_*rez 0 iphone objective-c ios

我定义了以下变量:

@property (nonatomic, retain) NSMutableArray *arraySpeechSentences;
Run Code Online (Sandbox Code Playgroud)

我试图通过以下方式初始化它:

// Set the array of sentences to the stored array
NSMutableArray *speechSentences = [[NSMutableArray alloc] initWithArray:[tempDict objectForKey:key]];
arraySpeechSentences = speechSentences;
[speechSentences release];
Run Code Online (Sandbox Code Playgroud)

当我尝试调用[arraySpeechSentences count]时,应用程序崩溃了.但是,如果我按以下方式设置变量:

// Set the array of sentences to the stored array
NSMutableArray *speechSentences = [[NSMutableArray alloc] initWithArray:[tempDict objectForKey:key]];
self.arraySpeechSentences = speechSentences;
[speechSentences release];
Run Code Online (Sandbox Code Playgroud)

我可以完美地调用[arraySpeechSentences count].我的印象是,如果你使用自我.它只是检查变量是否已经设置,如果是,它将在为其赋值之前释放该对象.我有这个错误,如果是的话,我什么时候应该使用自己.设定价值?

感谢您的帮助,Elliott

Jes*_*sak 7

使用setter(如self.foo = ...[self setFoo:...])会释放旧值,但它也会保留新值,这在您给出的示例中是必需的.

问题是你要分配并初始化你的数组,然后释放它.这表明您不再需要它.因此,您应该使用setter(通常更可取)或不释放您的数组.