开发者

NSArray release crashes with EXC_BAD_ACCESS

Another puzzler. I have an N开发者_Python百科SArray (iTours) containing 3 Objects and a retain count of 1.

This Array is released in the object dealloc method as follows:

- (void)dealloc {
    NSLog(@"retain count für iTouren: %d", [iTours retainCount]);
    [iTours release];  // triggers EXC_BAD_ACCESS 
    [super  dealloc];
}

The console window shows the following message (no further details):

Program received signal: “EXC_BAD_ACCESS”.

any clues what's going on? What did I miss?


Most likely, you are over-releasing iTouren and, thus, that call to release is causing the crash. That is, iTouren is already deallocated by the time you release the containing array and when that containing array sends release to the already deallocated iTouren your app crashes.

(Of course, iTours might be the object that is already deallocated. In any case, it is an over-release problem.)

Turn on zombie detection and see if that barfs up the specific problem.

Note that the

number returned by retainCount is useless

. Absolute retain counts are an implementation detail and will often be a specific value that seems like nonsense.

In this case, the final release of an object does not decrement the retain count. Why? Because that'd be a wasted cycle when the object is about to be deallocated anyway. It would be impossible for retainCount to return 0 because, by definition, an object with a retain count of 0 has already been deallocated and, thus, is no longer a viable message receiver anyway.


Never, ever, ever, rely on the retainCount method.

Ever.

Did I mention ever?


One is iTours the other one iTouren. You are logging a different object than that being released.


Assuming iTours and iTouren are different objects (namely that iTours is an NSArray containing iTouren), you've over-released iTours; maybe you had a failure in a setter and iTours was released without being reassigned and retained.


Be sure that your array does not contains itself. Releasing an array also release every object in it. Of course, if this is the case, the array should have a release count of two before you release it because arrays retain their elements.


A released and deallocated object will have a retain count of 1. A non-released object about to be released and deallocated will also have a retain count of 1. (Assuming memory is ever allocated for the object, some strings and numbers are never allocated, implementation detail that changes per Mac OS X release)

When an object is deallocated in current versions of Mac OS X, the memory is marked as free, nothing about the object is modified (unless you tell it to be). Thus, the retain count remains identical to the retain count before it was released.

This is the make a mistake and DIAF approach that help makes Mac OS X so solid.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜