开发者

How to call a method of another class [duplicate]

开发者 https://www.devze.com 2023-01-04 19:42 出处:网络
This question already has answers here: 开发者_Go百科 What is the difference between class and instance methods?
This question already has answers here: 开发者_Go百科 What is the difference between class and instance methods? (18 answers) Closed 2 years ago.

I would like to call the method mymethod of class b, using the method currentMethod of class a. How do I do this?


Given:

@interface B : NSObject
- (void) myMethod;
@end
@implementation B
- (void) myMethod {
    ... do something ...
}
@end

Then you could do:

@implementation A
- (void) currentMethod {
   [[[B new] autorelease] myMethod];
}
@end

Of course, that is exceedingly unlikely to do what you want. In particular, that would cause a new instance of B to be instantiated on each call to currentMethod. I would bet that your question is more along the lines of "I have an instance of Object A and an instance of Object B from somewhere else in my program, how do I message B from A?"

Ultimately, you should read the Objective-C programming guide to understand how classes and instances work. From there, you will need to understand how iPhone applications are architected to understand where your various instances go and how they get a hold of each other.


You have to :

1/ Put the method you want to call in the interface @interface B

-(void)methodB;

2/ You have a reference to the object that you want to call the method. Like initWithModel:

@interface A

B _b;

implementation A

initWithB:(B b)

_b = b;

[_b methodB];

0

精彩评论

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