Reputation: 8066
I created 2 objects subclass from NSObject
AObject, BObject
Is it possible to transfer 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
Upvotes: 2
Views: 128
Reputation: 185962
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 *
(or id
, as suggested in the comments) and query the type inside the function.
BaseObject *
, from which AObject
and BObject
inherit.Combine the base class with a trampoline technique:
- (void)myFunction:(BaseObject *)base {
[base myTrampoline:self];
}
BaseObject
declares the abstract method myTrampoline:
, which AObject
and BObject
implement.
Without knowing more about your problem, it's impossible to say which is best.
Upvotes: 2
Reputation: 18375
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>
}
//...
Upvotes: 1