Chewie The Chorkie
Chewie The Chorkie

Reputation: 5234

Passing nil object pointer in Objective-C

I create an object which I set to nil by default before including it in a method as a parameter. I do a check later if the object is still nil or not. The object is set to change in the method but the result is still nil. I'd expect the method to be able to alter the nil object. If I have the code that's inside the method replace the method call, it results in it being NOT nil.

MyObject *objectTemp = nil;

[self methodCallWithObject:objectTemp];

if  (objectTemp == nil) NSLog(@"nil");
else NSLog(@"NOT nil");

// always results in "nil"

method:

-(void) methodCallWithObject:(MyObject)objectTemp {

    objectTemp = [NSValue valueWithCGPoint:CGPointMake(5.3f, 2.6f)];

}

Upvotes: 0

Views: 235

Answers (1)

mipadi
mipadi

Reputation: 410732

In order to change objectTemp outside of the method, you have to pass a pointer to objectTemp, which means that methodCallWithObject actually needs to take a pointer to a pointer:

-(void) methodCallWithObject:(MyObject **)objectTemp {
    *objectTemp = [NSValue valueWithCGPoint:CGPointMake(5.3f, 2.6f)];
}

(However, it would probably make more sense to have methodCallWithObject just return a new object.)

Upvotes: 4

Related Questions