0

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?

1
  • Note: If your string is actually saying "undefined" it's likely you got it from a Javascript API which passes nil as literal text 'undefined', you can just use isEqualToString:"undefined" to check against this Commented Oct 16, 2020 at 6:26

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
No, C doesn't alloc the memory. See the clarification I added.
1

declare MyObject to be nil:

MyObject *myObject = nil;

That way it doesn't do anything.

Comments

0

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

MyObject * myObject = nil;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.