2

Imagine I have two protocols:

@protocol A
@end

and

@protocol B <A> // Protocol B conforms to protocol A.
@end

And also two variables:

id<A> myVar = nil;

and

id<B> otherVar = //correctly initialized to some class that conforms to <B>;

Then, why can't I assign 'otherVar' to 'myVar'?

myVar = otherVar; //Warning, sending id<B> to parameter of incompatible type id<A>

Thanks!

LuisCien
  • 6,362
  • 4
  • 34
  • 42
  • did you try casting the variable? – Bot Apr 05 '12 at 21:24
  • I can't reproduce this. Are the protocols in separate files? What headers are you importing and where? – hooleyhoop Apr 05 '12 at 22:39
  • Yes, the protocols are in separate files. The problem was with the visibility of the files. I was using a forward declaration when I should have imported the file. – LuisCien Apr 10 '12 at 17:44

2 Answers2

1

Is the protocol's (B) declaration (not just its forward declaration) visible? And does the declaration precede myVar = otherVar;?

When the declaration order is correct, clang did not complain.

To illustrate:

@protocol A
@end

@protocol B; // << forward B

void fn() {
    id<A> myVar = nil;
    id<B> otherVar = nil;
    myVar = otherVar; // << warning
}

// declaration follows use, or is not visible:    
@protocol B <A>
@end

whereas the properly ordered version produces no warning:

@protocol A
@end

@protocol B <A>
@end

void fn() {
    id<A> myVar = nil;
    id<B> otherVar = nil;
    myVar = otherVar;
}
justin
  • 104,054
  • 14
  • 179
  • 226
0

Check if it conformsToProtocol() and if so then cast it like so

myVar = (id <A>)otherVar;

A similar question can be viewed at Cast an instance of a class to a @protocol in Objective-C

Community
  • 1
  • 1
Bot
  • 11,868
  • 11
  • 75
  • 131