arachide
arachide

Reputation: 8066

different type Objects as parameter of a function

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

Answers (2)

Marcelo Cantos
Marcelo Cantos

Reputation: 185962

There are several options. Here are four that come to mind, each with their own pros and cons:

  1. Discriminate by signature:

    - (void)myFunctionWithA:(AObject *)obj;
    - (void)myFunctionWithB:(BObject *)obj;
    
  2. Declare a parameter of type NSObject * (or id, as suggested in the comments) and query the type inside the function.

  3. As above, but constrain it by declaring a common base class BaseObject *, from which AObject and BObject inherit.
  4. 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

Jonathan Sterling
Jonathan Sterling

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

Related Questions