【问题标题】:Objective C typedef Enum memory managementObjective C typedef枚举内存管理
【发布时间】:2012-05-27 09:17:15
【问题描述】:

在处理枚举时是否需要注意内存? 这是我声明我的枚举类型的地方。它在另一个 .h 文件中 这是我尝试声明变量的地方
在那之后我有没有做类似的事情

// This is where I declared my enum type. It is in another .h file

    typedef enum CardTypes
    {
        HEART = 1,
        DIAMOND =2,
        CLUB =3,
        SPADE = 4

    } CardType;

    // This is where I attempt to declare variable  

    CardType cardType=SPADE;

    //or

    CardType cardType=malloc(size(CardType));

    // After that Do I have o do something like that

    [cardType release]

    //or

     free(&card)

     Any help will be appreciated , thanks

【问题讨论】:

    标签: objective-c memory-management enums dealloc alloc


    【解决方案1】:

    这只是一个基本的 C 类型 - 在这方面它的处理方式就像 int

    这是自动的:

    CardType cardType=SPADE;
    

    但是当你发现你必须使用malloc,那么你就需要free它。

    通常(例如参数、ivar、局部变量),您会按值声明枚举,但(如int)您可能偶尔需要使用malloc+free

    【讨论】:

      【解决方案2】:

      CardType type = SPADE - 在堆栈上分配内存(不需要内存管理)

      CardType *type = malloc(sizeof(CardType)) - 在堆上分配内存(提到一个指针 *),因为显式分配,你负责使用 free(type) 释放内存

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-27
        • 1970-01-01
        相关资源
        最近更新 更多