gpt4 book ai didi

ios - 如何使用 NS_ENUM

转载 作者:行者123 更新时间:2023-11-29 05:40:51 26 4
gpt4 key购买 nike

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

typedef NS_ENUM(NSInteger, TABLE_SECTION_ITEMS)
{

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

};

最佳答案

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

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

TABLE_SECTION_Count
};

我们不指定值,因为这可能会破坏逻辑。但您可以对项目重新排序,也可以通过将项目放在“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 可能到达非 void 函数的末尾)。因此,作为开发人员,您被迫填写如下:

- (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
};

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

关于ios - 如何使用 NS_ENUM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56573368/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com