user2957392
user2957392

Reputation: 31

How to conform to two protocols defining a method with the same name and different signature?

I am using iOS7's new feature, MultipeerConnectivity. It comes with a function didChangeState:

in ViewController.h,

#import <GameKit/GameKit.h>
#import <MultipeerConnectivity/MultipeerConnectivity.h>
@interface ViewController : UIViewController <GKPeerPickerControllerDelegate, GKSessionDelegate, MCBrowserViewControllerDelegate, MCSessionDelegate>

in ViewController.m, both of the following methods are required to implement:

- (void)session:(MCSession *)session peer:(MCPeerID *)peerID didChangeState:(MCSessionState)state{ ...... }

// which the name is duplicate to iOS6 Gamekit function:

- (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state { ...... }

since iOS does not support function overloading, how should I include both functions in the same program? It is failed to compile. Error: Duplicate declaration of method 'session:peer:didChangeState:' I am using latest XCode 5.0.1.

Upvotes: 3

Views: 732

Answers (1)

Gabriele Petronella
Gabriele Petronella

Reputation: 108151

The issue is not coming from importing the two frameworks, but from your class conforming to both GKSessionDelegate and MCSessionDelegate. Implementing those two methods in the same class is something you cannot do since they have the same name.

You will have to use two different classes, one conforming to GKSessionDelegate and one to MCSessionDelegate.


Original answer

Just go ahead and include them.

Importing two classes defining a method with the same name is by no means method overloading.

Overloading occurs when defining multiple methods with the same name but different signature on the same class hierarchy, which is not the case here (and it will never be, since it's forbidden in Objective-C)


The only issue you might have is the compiler not being able to correctly type check when you don't provide enough information.

For instance if you do

id anObject = //... retrieve the object
[anObject session:aSession peer:anId didChangeState:aState]

the compiler will warn you that he's not able to understand which of the two methods you are calling, since there's no information on the type. A simple cast will quiet the compiler.

At runtime, though, you won't have issues, since the type will be dynamically resolved.

As an example, you can refer to this recent question: How to get rid of the "Incompatible pointer types" warning?

Upvotes: 9

Related Questions