三个关于objective-c内存管理的疑惑,希望能有人帮我解答
PHPz
PHPz 2017-04-24 09:12:06
0
2
361

疑惑:
1、内存管理:dealloc之后还能打印出retainCount = 1
main方法中:

person方法中覆写的dealloc方法和打印结果

2、 两个 category都只覆写了dealloc方法,用来输出验证
Copy创建的对象release之后调用dealloc方法,但是在自动释放池释放对象时,又释放了一次
为什么会释放两次啊?

3、使用类名方法创建对象,引用计数为2

PHPz
PHPz

学习是最好的投资!

reply all(2)
阿神
  1. Extraordinary melon seeds’ answer is right.

  2. YesNSMutableArray对象调用copy返回的是一个NSArray对象,所以在[array4 release]被调用时array4的dealloc方法被调用,输出NSArray dealloc.
    Then the autoreleasepool is destroyed, array3 is released, and the dealloc method of array3 is called. Because [super dealloc] is called in the dealloc method of NSMutableArray, the following two sentences are output.

  3. According to the answer on StackOverflow, this is because NSArray is an immutable object, and the reference count of this empty array instance will be increased by [NSArray array]或者[[NSArray alloc] init]生成的都是不可变的空数组,所以苹果默认所有不可变空数组的引用都指向一个唯一实例以进行优化,所以在[NSArray array]之前,这个实例的retainCount就是1了。在代码中不论是[NSArray array]或者[[NSArray alloc] init].

The following code can reflect this more intuitively, with a无关的[NSArray array]语句增加了areference counting.

NSArray *a = [[NSArray alloc] init];
[NSArray array];
[NSArray array];
NSLog("retainCount = %ld", a.retainCount);//输出结果为4

If ARC is not turned on, memory management only needs to follow the four "golden rules" in the basic memory management rules in Apple documents.

Ty80

Answer the first question
The object's memory has been reclaimed during output.
When sending a retainCount message to an object that has been recycled, the output result should be uncertain. If the memory occupied by the object is reused, it may cause the program to crash abnormally.
Why is this indeterminate value 1 instead of 0? Because when release was executed for the last time, the system knew that the memory was about to be recycled, so there was no need to decrement release时,系统知道马上要回收内存,就没必要将retainCount by 1, because the object would definitely be recycled regardless of whether it was decremented by 1 or not.
Not changing this value from 1 to 0 can reduce one memory operation and speed up object recycling.
Conclusion: Don't send messages to objects that have been released.

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