Can I use self = nil in my methods?
Can I use
self = nil
in an instance m开发者_StackOverflow社区ethod 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
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.
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.
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.
精彩评论