开发者

How to call a method through the object created by interface in Objective-C

I need to call a method through the object created by the interface ie

id<MyProtocol>obj;

Now i have created this obj in my main class where i am not implementing the methods of this protocol but i need to access the method which is already implemented in someother class.I am now calling the method as follows

[obj load]; 

in my main class in the applicationDidFinishLaunching, but i not able to access the method? Pls do sugges开发者_运维知识库t me the correct way of calling the methods through protocols...


A protocol implements nothing. It only describes a set of messages that the object should respond to. Your obj object belongs to some class. This class needs to implement methods described in MyProtocol.

Edit

A protocol is not implemented by a specific class. Any class that claims to conform to a protocol must implement its methods. Any object that claims to conform to a protocol must belong to a class that implements its methods.

In your case, obj is a ClassB, so ClassB must implement methods described by MyProtocol, either directly or through inheritance.


[obj load] is OK. If you want to shut up the compiler you can cast it to id:

[(id)obj load];

But if you know you'll need to call the -load method, maybe you should add the -load method to the protocol, or make another protocol that has the -load method e.g.

@protocol Loadable
-(void)load;
@end

...
id<MyProtocol, Loadable> obj;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜