aneuryzm
aneuryzm

Reputation: 64834

Can I use self = nil in my methods?

Can I use

self = nil 

in an instance method so that when the method execution ends, I can use an if statement in the main class:

if (myInstance) 

to check if something went wrong ?

thanks

Upvotes: 3

Views: 2675

Answers (3)

justin
justin

Reputation: 104698

You can do that, but it does not have the effect you want.

consider your objc method's signature for -[NSArray count] to have the following C function signature:

NSUInteger NSArray_count(NSArray * self, SEL _cmd) {
   self = nil; // ok - this is a variable, local to the function (method).
               // now all messages to `self` will do nothing - in this method only.
   ...
}

since the pointer you assign to nil is a variable local to the method, it does not actually affect the instance externally. it changes the pointer variable in the method's scope. that variable is the argument passed. in effect, it means that you have set the local argument to nil, but the rest of the world does not acknowledge this change.

Upvotes: 4

Jaffa
Jaffa

Reputation: 12710

You can return nil from a constructor, but if you return nil the maybe-allocated memory will never be freed!

If you're object manages its own life-cycle (and thus memory management), you can release it and return nil from a specific method. Usually that kind of methods are class method, because if it isn't it involve that the user has a reference to the object, and thus it is hazardous to release it.

Upvotes: 0

Jesse Bunch
Jesse Bunch

Reputation: 6679

You can return nil in the constructor, yes. If you do this after calling the [super init] be sure you release the object it returned with an owning retain count.

With that said, something else you can do is follow Apple's usage of *NSError to go along with returning nil to help provide better information of what went wrong to your using code.

Upvotes: 0

Related Questions