Victor Ng's Radio Weblog : armed with cocoa, an ibook and too much spare time
Updated: 4/4/03; 12:24:27 AM.

 

Click to see the XML version of this web page.

Click here to send an email to the editor of this weblog.


dotMac


Categories

Cocoa


Friends


Site Meter
 
 

Saturday, December 28, 2002

Common gotcha of the day in Cocoa:

Pointers don't initialize to 'nil'.

This will kill you in the usual ways that you expect in C - all your pointers will get indeterminate values unless you explicitly assign nil to them.

This is only a little painful if you properly use the designated initializer idiom to set all your instance pointers to 'nil' right away. Keep in mind that after an object is released, the pointer is not set to 'nil'.

That means that although:

[myObject someMessage:arg1 withExtraArg:arg2];

will not product an error if myObject is properly set to 'nil', it will produce a SIGBUS error (signal 10) if you did this:

myObject = [[MyClass alloc] init];
[myObject release];
[myObject someMessage:arg1 withExtraArg:argt];

Something you may consider safer would be to do something like this:

myObject = [myObject release];

which would assign 'nil' to your object upon object deallocation - but it won't work. Remember that the release message doesn't really release the object, it's sending a 'decrement reference count' message to the object. If the ref count happens to reach 0 - the object will be deallocated.

By incorrectly assigning 'nil' every time you 'release', you'll get dangling objects in memory that will never properly go away.

On the otherhand, if you do happen to know that an object's lifecycle should complete - then you probably should just assign 'nil' to the pointer.

In practice - it seems like as long as you initialize pointers to 'nil' - you don't really have many problems. By the time you get to a 'release' message, you're either in a deallocation method or you're shuffling objects between collections.

Always keep in mind that Objective-C is not 'sandboxed' like Java is. If you make a bad pointer operation - you can thrash memory in areas that you're not expecting. I'm not 100% sure - but it seems like ProjectBuilder can become erratic and crash if you do bad pointer programming.
9:54:18 AM    


© Copyright 2003 Victor Ng.



Click here to visit the Radio UserLand website.

 


December 2002
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31        
Nov   Jan


AIM: vng1@mac.com
MSN: v2ng@hotmail.com
ICQ: 30390174

NetNewsWire: More news, less junk. Faster