different type Objects as parameter of a function
I created 2 objects subclass from NSObject
AObject, BObject
Is it possible to trans开发者_如何学编程fer variables of these 2 objects to a same function?
such as
-(void)myFunction:(AObject *)obj;
-(void)myFunction:(BObject *)obj;
I tested in xcode, it is not allowed. Is there any replacement method?
Welcome any comment
Thanks interdev
There are several options. Here are four that come to mind, each with their own pros and cons:
Discriminate by signature:
- (void)myFunctionWithA:(AObject *)obj; - (void)myFunctionWithB:(BObject *)obj;
Declare a parameter of type
NSObject *
(orid
, as suggested in the comments) and query the type inside the function.- As above, but constrain it by declaring a common base class
BaseObject *
, from whichAObject
andBObject
inherit. Combine the base class with a trampoline technique:
- (void)myFunction:(BaseObject *)base { [base myTrampoline:self]; }
BaseObject
declares the abstract methodmyTrampoline:
, whichAObject
andBObject
implement.
Without knowing more about your problem, it's impossible to say which is best.
It's been suggested to just type your parameter as id
, but if you are feeling awesome, you can enforce compile-time checking that your object will actually be able to do what you need: use a protocol.
@protocol DoingSomething <NSObject>
// whatever methods you intend to call on the parameter of that one method
@end
//...
- (void)myFunction:(id<DoingSomething>)param {
// only send messages to param that are in <DoingSomething> and <NSObject>
}
//...
精彩评论