我的应用程序中有一个 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;
@end
Account.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]
.解决这个问题的最佳方法是什么?
最佳答案
首先,amount
不太可能应该有类型 NSInteger *
, 那是一个指向一个整数的指针,它更有可能只是NSInteger
, 那是一个整数。 NSInteger *
的所有其他用途也是如此.这是因为 amount
是一个值 而不是对对象的引用,不像你说的withdrawal
返回对象引用的属性。
Ideally, what I'd like to is to be able to call
[[account withdrawal] withdraw:50]
and have[account amount]
be updated as well. What's the best way to tackle this?
在不评论设计的情况下,如果您的取款对象需要访问您的帐户对象,那么它需要一个(获取方式)引用它。你应该考虑 Withdrawal
类具有其关联的属性 Account
, 就像你的 Account
具有其关联的属性 Withdrawal
.例如,您可以在创建 Withdrawal
时设置它对象,您当前所在的位置:
_withdrawal = [[Withdrawal alloc] init];
变成:
_withdrawal = [[Withdrawal alloc] initWithAccount:self];
这样做可能会导致您创建一个循环 - 每 Account
实例引用 Withdrawal
实例,它又引用了 Account
实例。循环本身并不坏,只有当它们阻止不需要的对象被收集时它们才会变坏。但是我怀疑你的 Account
将以 closeAccount
结尾方法,您可以在其中根据需要打破任何循环。
希望这会给你一些东西去继续工作。如果您发现您的设计/代码不起作用,请提出一个新问题,详细说明您设计和编码的内容以及您的问题所在。
关于ios - 从类(class)到父类(class)沟通?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37225053/