ios - 从类(class)到父类(class)沟通?

标签 ios objective-c

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

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/

相关文章:

ios - 如何在ios中找到一个元素的 child ?

ios - 从文档目录获取图像到 Collection View

objective-c - UIViewAnimation 导致从枚举类型隐式转换

iOS 后台获取模式可用于安排将来某些实际上并不获取远程数据的操作?

ios - KVO 在单例属性(property)上?

objective-c - 解析包含多个数组的 json 响应以填充 ios 中 tableView 的单元格

objective-c - iOS:在 View 之间传递数据

ios - 从信标确定 iDevice 的距离和方向

ios - Css - 使用 factorized css iphones 4 及更高版本的目标

objective-c - 带有类别的 NSManagedObjects