objective c help - calling methods?
Hey, I am new to programming I wanted to know why is it always [self method];? I mean why is it that way could someone explain me why is it self and what is going on in the background? sorry if 开发者_C百科it is a stupid question
thanks, TC
Basically, what self
refers to is the object that you're currently in the context of. [self somemethod]
means that you're invoking a method named somemethod
in the class that self
was initialized as.
For example, if you were to do something like this:
Foo *f = [[Foo alloc]init];
[f someMethod];
You'd be invoking someMethod
on the Foo
instance.
But if you're working inside of the class Foo
, self serves as an explicit reference to the current object. In this case, you'd simply use [self someMethod]
to invoke someMethod
.
-(id) init {
if (self = [super init]) {
[self someMethod];
}
...
}
-(void) someMethod { }
Does that help?
[self method] calls the method of the calling class. For example, in the header file of your class,
@interface YourClass : NSObject {
}
- (void) myMethod;
then, you can call the 'myMethod' in YourClass by using [self myMethod]. Does it make sense?
- During calling [self method], there is no any background working. [self method] is almost same the calling function in C. When you use [self method], 'method' in your class is just called right away.
Because [self method];
calls the -method
method in the class from which it is called.
If you want kill John in ObjC:
[john sendBullet]
if you do sendBullet to myself
(shortly self), it's a suicide
[self sendBullet]
got the difference? :)
精彩评论