Reputation: 171
In the following code
id<SwiftProtocol> anotherInstanceAsProtocol = [[SomeObjectiveCClassImplementingOBJCSwiftProtocol alloc] init];
[anotherInstanceAsProtocol isKindOfClass:[SomeObjectiveCClassImplementingOBJCSwiftProtocol class]];
I get the warning "No known instance method for selector 'isKindOfClass:'"
If I modify the last line to
[(id)anotherInstanceAsProtocol isKindOfClass:[SomeObjectiveCClassImplementingOBJCSwiftProtocol class]]
It runs perfectly.
It also works if I assign to NSObject<SwiftProtocol>
instead of id<SwiftProtocol>
, but I think neither should be necessary.
Why is this cast necessary?
Upvotes: 1
Views: 236
Reputation: 130162
The problem is that your SwiftProtocol
does not inherit from NSObject(Protocol) therefore the Obj-C compiler does not know that there is a method called isKindOfClass:
.
Using id
basically means you don't want any type checking at compilation time. The real fix should be to make the protocol extend NSObjectProtocol
, making sure that all instances conforming to it are normal Obj-C objects.
Note that the history of Objective-C is complicated and not all Objective-C objects have to inherit from NSObject
and have isKindOfClass:
available.
Upvotes: 3