开发者

How to do I pass self as a method parameter ?

I need to pass self into a method, how do I do it ?

I don't know what type of obje开发者_Python百科ct self is ?

I've tried :(id)dg


When you are inside an @implementation block for a class Foo, self is Foo*. This means that you can type the method parameter as Foo* or id (= any object, no type checking done):

@class Foo, SomeCollaborator;

@interface SomeCollaborator
- (void) doSomethingWithMe: (Foo*) myself;
- (void) doSomethingWithMe2: (id) myself;
@end

@implementation Foo
- (void) someFooMethod {
    [someCollaborator doSomethingWithMe:self];
}
@end


That seems right to me. (id) represents all possible objects.

Here's some code that works:

@implementation Inspector
- (void)printClassOf:(id)instance {
    NSLog("instance is of class: %@", [instance class]);
}
@end

@implementation SomeClass
- (void)someMethod {
    Inspector *myInstance = [[[Inspector alloc] init] autorelease];
    [myInstance printClassOf:self];
}
@end


What is the signature of the method (in other words, how is the method defined in the interface)?

Or do you mean, you want to define a method in class B to allow an instance of class A to call that method and pass in itself as one of the parameters? If so, :(id)sender is often used as a generic way to do that. For example, in NSWindow,

- (void)makeKeyAndOrderFront:(id)sender;
- (void)orderFront:(id)sender;
- (void)orderBack:(id)sender;

Within the implementation of that method, you can do something like this to help determine what to do:

- (void)makeKeyAndOrderFront:(id)sender {
   if ([sender isKindOfClass:[NSWindowController class]]) {
     // do something 

   } else if ([sender isKindOfClass:[MyCoolClass class]]) {
     // do something 

   } else if ([sender respondsToSelector:@selector(whyDidYouOrderMeFront)]) {
     // do something 

   } else if ([sender conformsToProtocol:@protocol(someCoolProtocol)]) {
     // do something 

   } else {
     // do something 
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜