iphone - 如何在objectiveC类中使用struct和union?

标签 iphone objective-c struct union

我正在尝试访问 Objective-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;  

最佳答案

你应该让它静态

@interface Account : NSObject {  
        union AccountData accountData;  
}

@property (nonatomic, assign) union AccountData accountData;  

否则您将需要在 init 中动态创建它(或将其设置为 NULL)。此外,您还需要确保结构中的所有这些 NSMutableString 指针都正确初始化为 nil 或其他。另外,您应该小心这里的内存管理,因为当您传递字符串时,字符串不会被保留(您可以覆盖结构的 setter/getter 来相应地保留/释放 NSMutableString)。

关于iphone - 如何在objectiveC类中使用struct和union?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8323479/

相关文章:

iphone - Xcode 4 存档未显示在管理器中

ios - iPhone WatchKit 配套应用显示名称

ios - 为所有 View Controller 编写一个通用方法,以在出现键盘时调整内容 View (UIScrollView)的框架

ios - 从头文件中获取实例函数

C++:如何使用初始化列表初始化内部结构的成员?

数组大小在编译时确定的 C 结构

iphone - 如何识别已呈现 UIViewController

iphone - iPhone、Android 和黑莓的移动开发

iphone - 让 CorePlot 条形图显示浮点值而不是整数?

c - 将结构数组分配给另一个结构成员时类型不完整