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

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.

主站蜘蛛池模板: 德庆县| 高州市| 家居| 威宁| 仪陇县| 分宜县| 盐山县| 宁津县| 昌平区| 河南省| 甘谷县| 鄂托克前旗| 巩留县| 金阳县| 巴中市| 新源县| 平潭县| 六枝特区| 伊金霍洛旗| 民权县| 自治县| 康保县| 安西县| 邹平县| 河源市| 花垣县| 南江县| 崇州市| 镇康县| 家居| 三原县| 广德县| 嘉祥县| 商丘市| 都昌县| 商都县| 儋州市| 云梦县| 信宜市| 谷城县| 西乌|