澄清分配后何时释放指针 [英] Clarification on when to release pointers after allocating

查看:70
本文介绍了澄清分配后何时释放指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的最后一个问题(此处)中,我有一个因为我释放了刚刚分配的变量而得到EXC_BAD_ACCESS的问题:

In my last question (here), I had an issue where I was getting an EXC_BAD_ACCESS because I was releasing the variable I had just allocated:

NSMutableArray* s = [[NSMutableArray alloc] init];
stack = s;
[s release];

应该是

NSMutableArray* s = [[NSMutableArray alloc] init];
stack = s;

但是,堆栈是我类的保留属性.声明如下:

However, stack is a retained property of my class. It's declared like so:

@interface StateStack ()
@property (nonatomic, retain) NSMutableArray* stack;
@end

给我的印象是,当您分配一个"retain"变量时,它会自动增加对象的retainCount.因此,应该从释放指针开始(如此处).

I was under the impression that when you assign a 'retain' variable, it automatically increments the retainCount of the object. So you are supposed to start by releasing your pointer (as here).

为什么这两种情况不同?谢谢!

Why are these two cases different? Thanks!

推荐答案

没有保留变量"之类的东西.这是保留的属性-意味着属性背后的setter方法将保留新值并释放旧值.但是赋值给变量只是赋值.实际上,人们通常建议直接在init中分配给实例变量的原因是为了使它不会通过设置器,因为设置器可能会产生您不希望在init中使用的副作用(当您的对象尚未完全构建.)

There is no such thing as a "retain variable". It's a retain property — meaning the setter method behind the property retains the new value and releases the old one. But assigning to a variable just assigns. In fact, the reason people generally recommend assigning directly to the instance variable in init is specifically so that it doesn't go through the setter, because the setter could conceivably have side effects you don't want in init (when your object isn't fully constructed yet).

注意:我在这里谈论的是正常的内存管理规则.如果您使用的是ARC,则一切都不同.但我想您会提到您是否曾经参加过.

这篇关于澄清分配后何时释放指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆