PDA

View Full Version : self = nil; (OBJECTIVE C) vs this = null (JAVA)




akabeer1983
Jan 20, 2009, 05:15 AM
hai,
in java, 'this' is a keyword that refers to the object on which the method containing the keyword 'this' is invoked.when we assign any value to 'this'
this = null;
it shows compile time error: CANNOT ASSIGN VALU TO FINAL VARIABLE 'this'

However, in Objective C, if i assign

self = nil;

it accepts.
Can anyone explain what happens as a result of this.

Example:
/*_____________main()_______________________*/

int main()
{
id OBJ_Alpha;
OBJ_Alpha = [[Alpha alloc]init];
[OBJ_Alpha SomeMethod];
[OBJ_Alpha PrintMethod]; //is this line equivalent to [nil PrintMethod]?
}


/*__________________class Alpha_____________________*/

@implementation Alpha
{}

-(void)SomeMethod
{
self = nil;
}

- (void) PrintMethod
{
printf("I am alive!!!");
}
@end


/*__________________________Example ends_____________*/

Will the PrintMethod work?



Eraserhead
Jan 20, 2009, 07:27 AM
I Imagine it will clear the pointer without freeing the memory of the object it is pointing at. That could be occassionally useful but I can't think of a case now. Generally you should use dealloc...

robbieduncan
Jan 20, 2009, 07:41 AM
The only time I've seen self=nil used is if something fails in your init method and you want to abort object creation. If you use it anywhere else I'd imagine very bad things will happen to your object and most likely your program.

MacRumors Guy
Jan 20, 2009, 08:48 AM
It's not "abort object creation", the object is already created just not initalized. The self pointer in objc is fundamentally different from that of java.

robbieduncan
Jan 20, 2009, 08:56 AM
It's not "abort object creation", the object is already created just not initalized.

OK, sure I agree with what you are saying: the memory space for the object has been allocated in the alloc call and the basic structure set up in the chained calls via [super init] up to NSObject.

hazmatzak
Jan 20, 2009, 09:13 AM
self and this are both object references. In Java, this is more special, in that the compiler won't allow you to assign to it, so you don't get yourself into trouble. But if you could, the same rule applies to all references: you're changing that reference, not affecting other references nor the object.

void foo(id someReference) {
id a, b;
a = someReference;
b = a;
a = nil;
if ( b == someReference ) printf("Not nil\n");
}

self is special because it is initialized at the start of a method to point to the object, and it is used to reference instance variables. But otherwise, it is just another local variable.

So when you assign nil in someMethod, it has no side effects, because you don't do anything after. (If you were to call that method again or any other method, self will be reinitialized.) And it certainly does not affect OBJ_Alpha in main, which still points to the object. So printMethod does get called.