Pointers in Cocoa
I don’t quite understand what Victor Ng is on about. Objective-C ivar pointers are initialized to nil, and you should get a compiler warning if you attempt to use an uninitialized local variable. [Michael Tsai[base ']s Weblog]
Mike sets me straight on Objective-C's initialization rules - sort've.
Suppose I have a class that is defined like this:
@interface VTNMyClass {
NSDate* aDate;
}
-(void)someMethod;
It turns out that when you allocate the object instance, the ObjC runtime will initialize all of your instance variables to 0 or nil.
To quote:
The alloc method dynamically allocates memory for the new object's instance variables and initializes them all to 0[~]all, that is, except the isa variable that connects the new instance to its class.
So what the heck was going on with my stuff? Here's my test case:
-(void)testIdInitTest
{
id obj;
[self assertTrue:(obj == nil) message:@"obj should be nil if pointers are initialized"];
}
.. and it always fails.
What's going on here is that (as the doc's say) the 'alloc' method is the thing doing the initialization. Since we never alloc an object, the 'obj' pointer is never initialized to nil.
Annoying - but true.
Regardless - thanks to Michael for pointing out my errors.
5:09:17 PM
|