// PROTOCOL
@protocol PetProtocol <NSObject>
- (void)printType;
@end
// CLASS
#import "PetProtocol.h"
@interface Animal : NSObject <PetProtocol> {
NSString *type;
}
@property (nonatomic, copy) NSString *type;
@end
下面是我用来测试的ViewController/viewDidLoad。
// WARNING: setType not found in protocol
id <PetProtocol> pet_001 = [[Animal alloc] init];
[pet_001 setType:@"DOG"];
[pet_001 printType];
我想我可以理解为什么我得到这个警告,因为“id”和“PetProtocol”都没有定义“type”属性。我有两个解决方案,但我只是想检查一下我是否做对了。我倾向于001作为使用id,然后铸造之前访问方法似乎是更好的选择,有谁愿意评论?
// 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];
编辑:
// 003
id pet_002 = [[Animal alloc] init];
[pet_002 setType:@"HAMSTER"];
[pet_002 printType];
非常感谢
加里。