我的应用程序中有一个Account类,它是用户的银行帐户。这初始化了两个名为Withdrawals和Deposits的类。它们看起来是这样的:
Account.h
@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;
@endAccount.m
@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]。解决这个问题的最好方法是什么?
发布于 2016-05-14 10:11:19
首先,amount不太可能有NSInteger *类型,它是一个指向整数的指针,它更有可能仅仅是NSInteger,也就是一个整数。NSInteger *的所有其他用途也是如此。这是因为amount是一个值,而不是对对象的引用,不像withdrawal属性那样返回对对象的引用。
理想情况下,我想要的是能够调用
[[account withdrawal] withdraw:50]并更新[account amount]。解决这个问题的最好方法是什么?
如果您的取款对象需要访问您的帐户对象,则需要(获取)对其的引用。您应该考虑Withdrawal类在其关联Account的属性中具有的属性,就像您的Account具有其关联Withdrawal的属性一样。例如,您可以在创建Withdrawal对象时设置此设置,其中当前:
_withdrawal = [[Withdrawal alloc] init];变成:
_withdrawal = [[Withdrawal alloc] initWithAccount:self];这样做可能会导致您创建一个循环--每个Account实例都引用一个Withdrawal实例,后者依次引用Account实例。循环本身并不坏,只有当它们阻止不想要的对象被收集时,它们才会变坏。不过,我怀疑您的Account最终会有一个closeAccount方法,在这里您可以根据需要中断任何周期。
希望这能给你一些东西,让你离开并继续努力。如果您发现您的设计/代码不工作,问一个新的问题,详细说明您已经设计和编码,以及您的问题是什么。
发布于 2016-05-14 10:15:08
这是一种构图关系,而不是亲子关系.要获得实际的存款额,您可以重写amount的getter:
- (NSInteger)amount {
_amount = // set left amount, this value should come from Withdrawal class
return _amount;
}顺便说一句,从*实例中删除NSInteger,使其成为一个简单的整数值,而不是指针。
https://stackoverflow.com/questions/37225053
复制相似问题