2012-08-12 49 views
0

有誰知道如何在目標c中添加屬性 - 但該屬性也是一個自定義類?如何在目標c中創建一個也是自定義類的屬性?

舉例來說,我做了這個類:

@interface Person : NSObject 

@property NSString *personName; 
@property NSNumber *personAge; 

-(id)init; 

@end 

哪裏..​​.

@implementation Person 

@synthesize personAge, personName; 

-(id)init{ 
    self = [super init]; 

    if(self){ 
     self.personAge = [NSNumber numberWithInt:26]; 
     self.personName = @"Jamie"; 
    } 
    return self; 
} 

@end 

所以基本上每當我初始化&頁頭Person類,它有人士獲取設置爲26和PERSONNAME作爲傑米。

現在我想創建一個包含個人財產銀行賬戶類:

@interface BankAccount : NSObject 

@property NSNumber *bankAccNumber; 
@property (nonatomic) Person *thePerson; 

-(id)init; 

@end 

哪裏..​​.

@implementation BankAccount 

@synthesize thePerson = _thePerson; 
@synthesize bankAccNumber; 

    -(id)init{ 

     self = [super init]; 

     if(self){ 
      bankAccNumber = [NSNumber numberWithInt:999]; 
     } 

     return self; 
    } 
    @end 

現在 - 我的問題是這樣的:

1)在BankAccount類中,我應該在哪裏分配& init Person類?

+0

您正在嘗試訪問BackAccount類中的Person類嗎? – 2012-08-12 13:55:10

+0

除了應用程序需要的內容外,沒有任何一個**正確答案。如果你只是想要默認的'Person',你當然可以在'bankAccNumber'上做同樣的地方。 (請記得導入Person.h。) – 2012-08-12 14:00:44

回答

1

要留在你的榜樣

@implementation BankAccount 

@synthesize thePerson = _thePerson; 
@synthesize bankAccNumber; 

-(id)init{ 

    self = [super init]; 

    if(self){ 
     bankAccNumber = [NSNumber numberWithInt:999]; 
     thePerson = [[Person alloc] init]; // <- **** HERE 
    } 

    return self; 
} 
@end 

當然,在一般情況下,你不希望每個人都成爲26yo Jamies,並有999 $,但我猜你打算以後改善這些細節:)

+0

這很好用 - 謝謝! – JamieS 2012-08-12 20:12:51

相關問題