2011-11-30 56 views
1

我正在嘗試訪問目標C類中的結構。但我是 不成功。任何人都可以解釋這個類是如何調整 使其編譯和訪問成員變量?如何在objectiveC類中使用struct和union?

#import <Foundation/Foundation.h> 

enum ACCOUNT_TYPE {  
     SAVINGS, 
     LOAN, 
     FIXED_DEPOSIT 
}; 

struct SavingsData { 
     NSMutableString* accountName; 
     NSMutableString* accountType; 
     NSMutableString* balance; 
     NSMutableString* currency; 
}; 

struct LoanData { 
     NSMutableString* accountName; 
     NSMutableString* balance; 
}; 

struct FixedDepositData { 
     NSMutableString* accountName; 
     NSMutableString* depositAmount; 
     NSMutableString* roi; 
}; 

union AccountData { 
     struct SavingsData *savingsData; 
     struct LoanData *loanData; 
     struct FixedDepositData *fixedDepositData; 
}; 

@interface Account : NSObject { 
     NSMutableString* accountId; 
     enum ACCOUNT_TYPE type; 
     union AccountData *accountData; 
} 

@property (nonatomic, assign) NSMutableString* accountId; 
@property (nonatomic, assign) enum ACCOUNT_TYPE type; 
@property (nonatomic, assign) union AccountData *accountData; 

回答

1

你應該有它的靜態

@interface Account : NSObject { 
     union AccountData accountData; 
} 

@property (nonatomic, assign) union AccountData accountData; 

否則,你將需要在初始化動態創建(或設置爲NULL)。你也需要確保你的結構中的所有這些NSMutableString指針都被正確初始化,否則爲零。此外,您應該小心內存管理,因爲在傳遞字符串時不會保留字符串(您可以重寫setter/getter以使結構保留/相應地釋放NSMutableString)。

+0

我試圖使用(。)運算符訪問變量。我想我必須使用accountData-> savingsData-> accountName。編譯。尚未在運行時嘗試...即將開始。感謝您的反饋如此之快。它有助於。 – Satish

2

嘗試以下(展示一個作爲一個例子,但適用於所有的),使用的typedef和移動的名義申報外....

typedef enum {  
     SAVINGS, 
     LOAN, 
     FIXED_DEPOSIT 
} ACCOUNT_TYPE; 

的使用...

ACCOUNT_TYPE type; 
AccountData accountData; 
1

我會建議使用typedef關鍵字:

typedef NS_ENUM(NSUInteger, ACCOUNT_TYPE) { 
    SAVINGS = 0, 
    LOAN, 
    FIXED_DEPOSIT 
}; 

typedef struct _SavingsData { 
     NSMutableString* accountName; 
     NSMutableString* accountType; 
     NSMutableString* balance; 
     NSMutableString* currency; 
} SavingsData; 

@interface Account : NSObject 

@property (nonatomic, strong) NSMutableString* accountId; 
@property (nonatomic, assign) ACCOUNT_TYPE type; 
@property (nonatomic, assign) SavingsData savingData; 

@end 

現在你可以使用這個類爲:

Account *acc = [Account new]; 
acc.type = SAVINGS; 
SavingsData savData = {..., ...}; 
acc.savingsData = savData; 
1

我建議像子類:

@interface Account : NSObject { 
    NSMutableString *accountId; 
    NSMutableString *accountName; 
} 
@end 

@interface SavingsAccount : Account { 
    NSMutableString *accountType; 
    NSMutableString *balance; 
    NSMutableString *currency; 
} 
@end 

@interface LoanAccount : Account { 
    NSMutableString *balance; 
} 
@end 

@interface FixedDepositAccount : Account { 
    NSMutableString *depositAmount; 
    NSMutableString *roi; 
} 
@end 

屬性被剪斷,並且帳戶名被移到基類賬戶,因爲它在所有3子很普遍。

+0

看起來不錯的設計。感謝您的建議。 – Satish