views:

80

answers:

1

Hello,

how to assign object of interface to a protocol's object? i've a protocolA and protocolB. all the methods of both the protocols is implemented in MyClass.How to restrict the access to only protocolA's methid and protocolB's methods ?Coding is done in Objective-C for iPhone application.

+2  A: 

On object creation you can just do this:

id <protocolA> protocolAObject = [[MyClass alloc] init];

Now, unless you use an explicit cast, you can't use protocolB methods.

You can also cast objects of class MyClass to either protocolA or protocolB like this:

MyClass *myClassObject = [[MyClass alloc] init];
id <protocolB> protocolBObject = (id <protocolB>) myClassObject;
Tom
hey... a wrote the your code in MyClass and assigned it to obj of protocolB. but using the object[protocolBobject] of protocolB i'm able to access the methods of other protocols also:(.but that shouldn't be the case right??
suse
There's no way of blocking the methods completely. But if you're trying to call protocolA methods, on an object of protocolB, you should get compiler warnings.
Tom
ok... but i'm able to access :(... give me some good links to read about its syntax, or links to example programs
suse
You might find these two links useful:http://developer.apple.com/Mac/library/documentation/Cocoa/Conceptual/ObjectiveC/Introduction/introObjectiveC.htmlhttp://www.otierney.net/objective-c.html
Tom
@Tom... In your second comment , you have mentioned that ***"if you're trying to call protocolA methods, on an object of protocolB, you should get compiler warnings"***, i've got a warning for same situation, but how would restrict it to only methods of protocolB???Is there any other method to solve this problem?
suse
Not sure I completely understand what you're trying to do, but as far as I know there's no way of completely blocking method access in Objective C.However compiler warnings are a bad thing, and you should avoid having any in your code. Compiler warnings should be enough to stop you calling methods that you shouldn't be calling.
Tom