官术网_书友最值得收藏!

Dangling pointers

Dangling pointers are the opposite of over-retained objects. You can encounter dangling pointers when trying to access a deallocated object. This is best illustrated by the following example:

- (void) doSomething {
MyObject *myObject = [[MyObject alloc] init]; // retainCount is +1
[myObject release]; // retain count is 0; object is deallocated

// More things happening in this method

[myObject myMethod];
}

This may not cause a crash all of the time, as myObject could be properly set to nil. When it crashes, you'll face the dreaded NSInvalidArgumentException, which, upon first glance, doesn't make much sense:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[<insert a type here> myMethod]: unrecognized selector sent to instance 0x12345679

We never have a call to myMethod on any other type. This crash often means that the contents of the memory at the myObject address have been replaced by some other object. Because we called release too early, the memory has been reclaimed, and potentially replaced by another object.

In order to overcome the burden of writing the manual reference counting, Apple introduced ARC. In the next section, we'll look at what this compiler feature can do, in order to provide efficient memory management.

主站蜘蛛池模板: 临清市| 上高县| 甘肃省| 鹤山市| 昌都县| 外汇| 长海县| 白城市| 准格尔旗| 怀宁县| 诏安县| 石台县| 海林市| 南京市| 双辽市| 大石桥市| 新邵县| 博兴县| 尉犁县| 巴东县| 瓦房店市| 鲁甸县| 民县| 永靖县| 阳新县| 前郭尔| 临颍县| 陈巴尔虎旗| 屏南县| 丹凤县| 镇赉县| 晴隆县| 岳西县| 合川市| 东城区| 抚顺县| 扎赉特旗| 邓州市| 莱阳市| 红安县| 蒲江县|