ios - 关于objective-c内存管理的一个疑问?
PHPz
PHPz 2017-04-17 11:56:14
0
4
673

如图示:不是说release调用之后对象内存就被释放了么?那为什么jack对象还能调用say方法[jack say]?

PHPz
PHPz

学习是最好的投资!

reply all(4)
Peter_Zhu

First of all, in the ARC era, it is not recommended that you manually manage reference counts

Let’s talk about this problem. In Objective-C, what the code directly controls is not the memory itself, but the reference count of this instance in the memory.
Therefore, after the alloc method initializes jack, jack's reference count is 1. The release method is called, which only decreases the reference count of the jack instance by 1 to 0.
A reference count of 0 does not mean that the instance is destroyed, but it is marked as "the instance can be destroyed".
If your code is written like this

Person *jack = [[Person alloc] init];
[jack release];
[jack say];
[jack say];
[jack say];
[jack say];
[jack say];
[jack say];
[jack say];

You will find that jack only said the previous sentence once or twice, and then he couldn't say it anymore.
Because the system recycling finds that jack can be recycled, and it takes a little time to reclaim this memory, and during this time, jack said once or twice.

Peter_Zhu

say does not access self, cpp has similar content

I searched, and my answer is wrong and must be corrected:
The key to being able to print correctly is that the object's memory has not been erased.
The calling mechanism of objective-c is different from that of cpp. I said that cpp has similar content and may mislead you.
When an objC message occurs [obj call], objc_msgSend will be called. For details, see: In-depth analysis of objc_msgSend

刘奇

The release in arc is useless.

迷茫

When the retainCount in ARC becomes 0, it will notify the system that the object is to be recycled. Sending and processing messages is an asynchronous process, which takes time

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template