Reputation: 26223
After setting up the following protocol, I have noticed that I am getting a warning when I try and access properties from the object:
// PROTOCOL
@protocol PetProtocol <NSObject>
- (void)printType;
@end
// CLASS
#import "PetProtocol.h"
@interface Animal : NSObject <PetProtocol> {
NSString *type;
}
@property (nonatomic, copy) NSString *type;
@end
The following is from a ViewController/viewDidLoad which I am using for testing.
// WARNING: setType not found in protocol
id <PetProtocol> pet_001 = [[Animal alloc] init];
[pet_001 setType:@"DOG"];
[pet_001 printType];
I think I can see why I am getting this warning as neither "id" nor "PetProtocol" define the "type" property. I have two solutions, but I just wanted to check I am getting this right. I am leaning towards 001 as using id and then casting before accessing the method seems like the better option, would anyone care to comment?
// 001
id <PetProtocol> pet_002 = [[Animal alloc] init];
[(Animal *)pet_002 setType:@"DOG"];
[pet_002 printType];
// 002
Animal <PetProtocol> *pet_003 = [[Animal alloc] init];
[pet_003 setType:@"CAT"];
[pet_003 printType];
I have just been looking at this and it seems to work better (i.e. no warning) without adding the protocol after the id?
// 003
id pet_002 = [[Animal alloc] init];
[pet_002 setType:@"HAMSTER"];
[pet_002 printType];
much appreciated
gary.
Upvotes: 1
Views: 461
Reputation: 181290
You need to add getter & setter to the protocol also (not only the class):
// PROTOCOL
@protocol PetProtocol <NSObject>
- (void)printType;
- (void)setType:(NSString*)val;
- (NSString*)type;
@end
Upvotes: 2