我正在尝试访问目标C类中的结构。但我是 不成功。任何人都可以解释如何调整这个类 使其编译和访问成员变量?
#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;
答案 0 :(得分:2)
尝试以下方法(显示一个例子但适用于所有人),使用typedef并将名称移到声明之外....
typedef enum {
SAVINGS,
LOAN,
FIXED_DEPOSIT
} ACCOUNT_TYPE;
你使用......
ACCOUNT_TYPE type;
AccountData accountData;
答案 1 :(得分:1)
你应该让它静止
@interface Account : NSObject {
union AccountData accountData;
}
@property (nonatomic, assign) union AccountData accountData;
否则,您需要在init中动态创建它(或将其设置为NULL)。此外,您需要确保结构中的所有这些NSMutableString指针都已正确初始化为nil或其他。此外,您应该小心内存管理,因为在传递字符串时不会保留字符串(您可以覆盖结构的setter / getter以相应地保留/释放NSMutableString)。
答案 2 :(得分: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;
答案 3 :(得分: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
属性被剪切,并且accountName被移动到基类Account,因为它在所有3个子类中都很常见。