tags:

views:

47

answers:

3

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?

A: 

Make sure you initialize your myObject to nil like so:-

MyObject * myObject = nil;

abdollar
+1  A: 

declare MyObject to be nil:

MyObject *myObject = nil;

That way it doesn't do anything.

Stephen Furlani
+2  A: 

In Objective-C, (or C in general),

 MyObject* myObject;

inside a method implementation does not initialize myObject with a nil. Similarly,

 int a;

does not initialize a with 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

 MyObject* myObject=nil;

Note that an ivar defined in the class interface is automatically set to zero before init is called.

Update: Also note that myObject is a pointer to the real object which contains data. So, if you just do

 MyObject* myObject;

this means myObject points to a chunk of garbage memory, which would not correctly work at all.

 MyObject* myObject=nil;

makes myObject to point to nothing. Now it at least consistently does nothing. What this line

 MyObject* myObject=[[MyObject alloc] init];

does is to allocate a MyObject object in the memory, initialize it, and then make myObject point to the chunk of memory correctly allocated and initialized. Now, if the MyObject has the interface

@interface MyObject:NSObject {
     NSString* string;
}
@end

and if you define the init method,

@implementation MyObject
-(id)init {
      if(self=[super init]) {
           ... do something ...
      }
      return self;
}

after [super init] is successfully performed, Objective-C guarantees that the ivar string is set to nil, i.e. string points to nothing. But it is not that an NSString is allocated or initialized.

Yuji
Thank you all..:)
stone
Wait, so then there isn't a point of using alloc when instantiating...I just have to use init. Since C already allocates memory to it. That's abit messed up. Isn't it? I shouldn't have to use nil when declaring
stone
No, C doesn't alloc the memory. See the clarification I added.
Yuji
thank you so much
stone