如何使用NS_ENUM

时间:2019-06-13 04:26:56

标签: ios objective-c enums

我想使用NS_ENUM。我已经在我的.m文件中编写了以下代码。现在,当我的cellForRowAtIndexPath被调用时。我得到了索引路径。现在对应于该索引路径,我想提取与其关联的字符串。例如对于索引路径0,我想提取图像。

typedef NS_ENUM(NSInteger, TABLE_SECTION_ITEMS)
{

    Images = 0,
    Videos = 1,
    Documents = 2,    
    Audios = 3

};

1 个答案:

答案 0 :(得分:0)

在这种情况下,我们通常要做的是始终将枚举中的最后一项保留为“ count”或“ last”。以您的情况为例:

typedef NS_ENUM(NSInteger, TABLE_SECTION_ITEMS)
{
    TABLE_SECTION_Images,
    TABLE_SECTION_Videos,
    TABLE_SECTION_Documents,
    TABLE_SECTION_Audios,

    TABLE_SECTION_Count
};

我们未指定值,因为这可能会破坏逻辑。但是您可以重新排序商品,也可以通过将商品放在“计数”之后来淘汰它们。

它的用法如下:

@interface ViewController()<UITableViewDelegate, UITableViewDataSource>

@end

@implementation ViewController

- (NSString *)tableSectionName:(TABLE_SECTION_ITEMS)item {
    switch (item) {
        case TABLE_SECTION_Images: return @"Images";
        case TABLE_SECTION_Videos: return @"Videos";
        case TABLE_SECTION_Documents: return @"Documents";
        case TABLE_SECTION_Audios: return @"Audios";
        case TABLE_SECTION_Count: return nil;
    }
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return TABLE_SECTION_Count;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.textLabel.text = [self tableSectionName:indexPath.row];
    return cell;
}

@end

因此行数只是TABLE_SECTION_Count,您可以自然地在NSInteger和您的枚举之间进行转换,如[self tableSectionName:indexPath.row]所示。

自然,仍然需要像tableSectionName中那样完成字符串的映射。它不是闲置的,但现在更易于管理;

当您添加新的枚举值(例如TABLE_SECTION_Documents2)时,您会在tableSectionName中收到n个错误,需要添加新的大小写(或者与之相关的错误,指出Control可能到达非无效函数的结尾)。因此,作为开发人员,您必须像这样填充它:

- (NSString *)tableSectionName:(TABLE_SECTION_ITEMS)item {
    switch (item) {
        case TABLE_SECTION_Images: return @"Images";
        case TABLE_SECTION_Videos: return @"Videos";
        case TABLE_SECTION_Documents: return @"Documents";
        case TABLE_SECTION_Documents2: return @"Documents";
        case TABLE_SECTION_Audios: return @"Audios";
        case TABLE_SECTION_Count: return nil;
    }
}

这里的另一个好处是我们可以拥有两次“文档”。 要弃用一项,我们要做的就是将枚举移到计数之后:

typedef NS_ENUM(NSInteger, TABLE_SECTION_ITEMS)
{
    TABLE_SECTION_Images,
    TABLE_SECTION_Videos,
    TABLE_SECTION_Documents2,
    TABLE_SECTION_Audios,

    TABLE_SECTION_Count, // Always keep last

    // Deprecated items
    TABLE_SECTION_Documents
};

现在,无需更改任何代码,旧的“文档”将不会在表格视图中列出。不理想,但仍然很整洁。

相关问题