Re: EXC_BAD_ACCESS in an strange place
Re: EXC_BAD_ACCESS in an strange place
- Subject: Re: EXC_BAD_ACCESS in an strange place
- From: Matt Neuburg <email@hidden>
- Date: Sun, 25 Aug 2002 16:56:52 -0700
On Thu, 22 Aug 2002 23:27:28 -0600, Clark Mueller <email@hidden> said:
>
> if( files == nil ){
>
> RunAlertPanel(@"Sorry, the operation can't continue.");
>
> return;
>
> }
>
>
>
> if( [files count] < 1 ){ // <<--- EXC_BAD_ACCESS happens here
>
it didn't, this is the weird part... A crash of this type would make me
>
believe that "files" is not initialized, and calling "count" on an
>
unallocated object causes the crash. But why doesn't the line right
>
above, to check for whether files is initialized catch that and tell me?
I bet you're coming from REALbasic, aren't you? You're certainly talking
like a REALbasic user. This is a real "gotcha" for such folks. In
REALbasic, a pointer to an object that gets released is repointed at nil.
In Cocoa, it isn't; it points at garbage.
And here's another part of the "gotcha". In REALbasic, sending a message to
nil causes an exception. In Cocoa, sending a message to nil causes nothing
at all. It's sending a message to garbage that causes the problem - and if
it happens, it's too late (and you get an EXC_BAD_ACCESS).
The solution, when you're a beginner, is to do all your setting and getting
of ivars (what a REALbasic user would call "properties") through accessor
functions. In particular, your setter should retain the new value, release
the old value, and set the ivar to point at the new value. Once you've done
that, never release an ivar; instead, set it to nil through the setter.
That way, it gets released *and* the pointer takes on a nil value that you
can test for.
Apart from this, just follow the basic rules of memory management (see
"Hold Me, Use Me, Free Me" for the best summary). I posted a good summary
for beginners here:
http://cocoa.mamasam.com/COCOADEV/2002/07/2/40541.php
m.
--
matt neuburg, phd = email@hidden,
http://www.tidbits.com/matt
pantes anthropoi tou eidenai oregontai phusei
Subscribe to TidBITS! It's free and smart.
http://www.tidbits.com/
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.