首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从一个班到另一个班交流?

从一个班到另一个班交流?
EN

Stack Overflow用户
提问于 2016-05-14 09:36:59
回答 2查看 41关注 0票数 0

我的应用程序中有一个Account类,它是用户的银行帐户。这初始化了两个名为WithdrawalsDeposits的类。它们看起来是这样的:

Account.h

代码语言:javascript
复制
@interface Account : NSObject

@property (nonatomic, copy) NSInteger *amount;
@property (nonatomic, strong) Withdrawal *withdrawal;
@property (nonatomic, strong) Deposit *deposit;

- (id)initWithAmount:(NSInteger *)amount;

- (Withdrawal *)withdrawal;
- (Deposit *)deposit;

@end

Account.m

代码语言:javascript
复制
@implementation Account

- (id)initWithAmount:(NSInteger *)amount {
    self = [super init];
    if (self)
    {
        _amount = amount;
        _withdrawal = [[Withdrawal alloc] init];
        _deposit = [[Deposit alloc] init];
    }
    return self;
}

- (Withdrawal *)withdrawal {
    return _withdrawal;
}

- (Deposit *)deposit {
    return _deposit;
}

@end

理想情况下,我想要的是能够调用[[account withdrawal] withdraw:50]并更新[account amount]。解决这个问题的最好方法是什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-05-14 10:11:19

首先,amount不太可能有NSInteger *类型,它是一个指向整数的指针,它更有可能仅仅是NSInteger,也就是一个整数。NSInteger *的所有其他用途也是如此。这是因为amount是一个值,而不是对对象的引用,不像withdrawal属性那样返回对对象的引用。

理想情况下,我想要的是能够调用[[account withdrawal] withdraw:50]并更新[account amount]。解决这个问题的最好方法是什么?

如果您的取款对象需要访问您的帐户对象,则需要(获取)对其的引用。您应该考虑Withdrawal类在其关联Account的属性中具有的属性,就像您的Account具有其关联Withdrawal的属性一样。例如,您可以在创建Withdrawal对象时设置此设置,其中当前:

代码语言:javascript
复制
_withdrawal = [[Withdrawal alloc] init];

变成:

代码语言:javascript
复制
_withdrawal = [[Withdrawal alloc] initWithAccount:self];

这样做可能会导致您创建一个循环--每个Account实例都引用一个Withdrawal实例,后者依次引用Account实例。循环本身并不坏,只有当它们阻止不想要的对象被收集时,它们才会变坏。不过,我怀疑您的Account最终会有一个closeAccount方法,在这里您可以根据需要中断任何周期。

希望这能给你一些东西,让你离开并继续努力。如果您发现您的设计/代码不工作,问一个新的问题,详细说明您已经设计和编码,以及您的问题是什么。

票数 1
EN

Stack Overflow用户

发布于 2016-05-14 10:15:08

这是一种构图关系,而不是亲子关系.要获得实际的存款额,您可以重写amount的getter:

代码语言:javascript
复制
- (NSInteger)amount {
   _amount = // set left amount, this value should come from Withdrawal class 
   return _amount;
}

顺便说一句,从*实例中删除NSInteger,使其成为一个简单的整数值,而不是指针。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37225053

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档