加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 为什么我只创建超类的属性才能使用子类

发布时间:2020-12-16 07:06:28 所属栏目:百科 来源:网络整理
导读:我正在关注斯坦福在线课程开发适用于iPhone和iPad的iOS 7应用程序( link to course in itunes U). 第一个作业要求学生创建一些课程中详细介绍的课程(卡片,PlayCard,Deck,PlayingCardDeck),并更新视图控制器以在一副扑克牌中显示随机卡片. 其中两项任务包括:
我正在关注斯坦福在线课程开发适用于iPhone和iPad的iOS 7应用程序( link to course in itunes U).

第一个作业要求学生创建一些课程中详细介绍的课程(卡片,PlayCard,Deck,PlayingCardDeck),并更新视图控制器以在一副扑克牌中显示随机卡片.

其中两项任务包括:

  1. Add a private property of type Deck * to the CardGameViewController.
  2. Use lazy instantiation to allocate and initialize this property (in the property’s getter)
    so that it starts off with a full deck of PlayingCards.

我在代码中添加了以下内容:

// CardGameViewController.m
#import "PlayingCardDeck.H"

@interface CardGameViewController ()
...
@property (strong,nonatomic) Deck *deck;
@end

@implementation CardGameViewController
- (Deck *)deck
{
    if (!_deck) _deck = [[PlayingCardDeck alloc] init];
    return _deck;
}
...
@end

提示表示以下内容:

  1. Even though the type of the property you must add is required to be a Deck (not PlayingCardDeck) you’ll obviously have to lazily instantiate it using a PlayingCardDeck. This is perfectly legal in object-oriented programming because a PlayingCardDeck inherits from Deck and thus it “is a” Deck. If you are confused by this concept in object-oriented programming,this course may be rather difficult for you.

PlayingCardDeck是Deck的子类.我知道它“是一个”甲板.

我不明白为什么使用Deck的属性而不是PlyaingCardDeck.

解决方法

使用Deck作为属性的类型可以使您的CardGameViewController更通用.如果您希望将来使用不同类型的卡组,您只需更改创建卡组的一行代码即可.

此外,如果您只是公开该属性,则可以使用不同类型的卡片创建不同的CardGameViewControllers,而不是使用PlayingCardDeckGameViewController和TarotCardDeckGameViewController以及PinochleCardDeckGameViewController等.

通常,使用Deck而不是PlayingCardDeck会为您打开更多选项并增加CardGameViewController的可重用性.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读