2016-05-14 23 views
0

我的應用程序中有一個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]也會被更新。解決這個問題的最好方法是什麼?

+0

@vadian你是對的。我重寫了示例以更好地匹配我的應用中的實際代碼。 – user4992124

回答

1

首先,它是不太可能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方法結束,你可以根據需要打破任何循環。

希望這會給你一些東西離開和工作。如果你發現你的設計/代碼不起作用,請提出一個新問題,詳細說明你設計的&代碼以及你的問題。

0

這是一個構成關係而不是孩子父母關係。要獲得帳戶的實際金額左邊你可以重寫amount的吸氣劑:

- (NSInteger)amount { 
    _amount = // set left amount, this value should come from Withdrawal class 
    return _amount; 
} 

順便說一句,從NSInteger的實例中刪除*,使之成爲一個整數值不是一個指針。