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

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.

主站蜘蛛池模板: 张北县| 建水县| 青州市| 尼勒克县| 荔浦县| 奉节县| 登封市| 潜山县| 威海市| 福安市| 抚顺市| 邢台县| 且末县| 阜新| 太保市| 普安县| 马关县| 安仁县| 公主岭市| 洛扎县| 瑞昌市| 桦甸市| 宣恩县| 凉山| 宁津县| 邳州市| 巫山县| 阿巴嘎旗| 岑巩县| 平阳县| 六枝特区| 锦州市| 万载县| 隆尧县| 东安县| 北安市| 安岳县| 渝北区| 佛坪县| 阿克| 玛纳斯县|