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.
isEqualToString:"undefined"to check against this