开发者

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:

  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.


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>
}
//...
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜