Ok, I created my own class(MyObject) subclassing NSObject
then in my code I declare this:
MyObject * myObject;
Then further down in my function, I do:
if(myObject == nil)
{
myObject = [self getObject];
}
My if statement returns false, which I want it to be true.
In debug mode: just declaring it is assigning an instance to it with some random values.
So, do I have to override the init function so it returns nil, and then create my own initWith function?
In Objective-C, (or C in general),
inside a method implementation does not initialize
myObjectwith anil. Similarly,does not initialize
awith 0. That’s what people who made C decided long ago. There was a historical rational why this was so.Just initialize it explicitly as
Note that an ivar defined in the class interface is automatically set to
zerobeforeinitis called.Update: Also note that
myObjectis a pointer to the real object which contains data. So, if you just dothis means
myObjectpoints to a chunk of garbage memory, which would not correctly work at all.makes
myObjectto point to nothing. Now it at least consistently does nothing. What this linedoes is to allocate a
MyObjectobject in the memory, initialize it, and then makemyObjectpoint to the chunk of memory correctly allocated and initialized. Now, if theMyObjecthas the interfaceand if you define the init method,
after
[super init]is successfully performed, Objective-C guarantees that the ivarstringis set tonil, i.e.stringpoints to nothing. But it is not that anNSStringis allocated or initialized.