Reputation: 399
Let's say I have a trivial class like this:
@interface ABPair : NSObject
@property id key;
@property id value;
- (void) printSize;
@end
@implementation ABPair
- (void) printSize {
NSLog(@"the size of your key is: %@", NSStringFromSize([self.key sizeWithAttributes: nil]));
}
@end
This compiles with no warnings (in Xcode 5), and runs successfully, and prints a reasonable value.
However, if I made this one change:
@property id<NSCopying> key;
then I get two compiler errors:
Why is the compiler able to identify the proper method (on NSString) when I provide no information at all about the type, but unable to identify the method when I say that the object must be of a protocol to which that class conforms?
Upvotes: 0
Views: 109
Reputation: 540005
id key
declares a "generic" Objective-C variable. It can point to any object,
and the compiler accepts any messages sent to it.
If you compile with ARC, it is only required that the message signature is known
to the compiler at all (from any class).
id<myprotocol> key
specifically declares a pointer to an object conforming to that protocol.
The compiler accepts only messages from the <myprotocol>
protocol (or other protocols that <myprotocol>
inherits from).
Upvotes: 3