objective-c protected instance variable

最近在做斯坦福公开课cs193p的课后练习Machismo,其中用到了类的继承。

[ccb_objc]
// GameViewController.h
@interface GameViewController : UIViewController
@property (nonatomic) Game *game;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *cardButtons;
@property (weak, nonatomic) IBOutlet UILabel *scoreLabel;
@property (weak, nonatomic) IBOutlet UILabel *messageLabel;
@end

// CardGameViewController.h
@interface CardGameViewController : GameViewController
@property (nonatomic) CardMatchingGame *game;
@end
[/ccb_objc]

[ccib_objc]CardGameViewController[/ccib_objc]是[ccib_objc]GameViewController[/ccib_objc]的一个子类。因为在子类中需要初始化[ccib_objc]@property (nonatomic) CardMatchingGame *game[/ccib_objc],所以就要在子类中访问基类中的instance variable,也就是[ccib_objc]_game[/ccib_objc]。如果这样尝试的话,编译器会给出一个错误。因为[ccib_objc]_game[/ccib_objc]是基类的private instance variable,子类是无法访问的。那如何才能将这个instance variable变为protected?只要将[ccib_objc]_game[/ccib_objc]在interface中声明即可。
[ccb_objc]
// GameViewController.h
@interface GameViewController : UIViewController {
Game *_game;
}
@property (nonatomic) Game *game;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *cardButtons;
@property (weak, nonatomic) IBOutlet UILabel *scoreLabel;
@property (weak, nonatomic) IBOutlet UILabel *messageLabel;
@end
[/ccb_objc]
在interface中声明的变量,默认都是[ccib_objc]@protected[/ccib_objc]。如果想定义为其他类型,可以使用[ccib_objc]@public[/ccib_objc]和[ccib_objc]@private[/ccib_objc]等关键字。这点和C++还是类似的。更多详细内容请参阅下面的资料。

参考

  1. How are declared private ivars different from synthesized ivars?
  2. Are synthesized instance variables generated as private instead of protected?
  3. Objective-C Access To Instance Variables
  4. Private properties, methods and ivars in Objective-C
  5. Objective-C Tuesdays: instance variables

发表评论

电子邮件地址不会被公开。 必填项已用*标注