将结构分配给 Objective C 中的 int 值

Assign a struct to an int value in Objective C

我想我想将一个部分索引和一个行索引一起打包成一个 int,并将结果分配给 UIView 的标签 属性。我以为我可以这样做但是它不起作用:

typedef struct
{
    int16_t section;
    int16_t row;
} SecRow;

SecRow sr = {2,3};
UIView* aview = [[UIView alloc] init];
[aview setTag:sr];//Error - Sending ‘SecRow’ to parameter of incompatible type ’NSInteger’ (aka ‘int’)
or
[aview setTag:(int32_t)sr];//Error - Operand of type ‘SecRow’ where arithmetic or pointer type is required

我知道这会限制部分和行的最大值,但我认为 16 位应该足够了。过去我会简单地将部分乘以 1000 或 10000 并将其添加到行中,但我想提出一种限制最少的方法来执行此操作。如果可以的话,我也想避免操纵位域。

我该怎么做?

您可以使用 union:

typedef union {
  struct {
    int16_t section;
    int16_t row;
  } fields;
  int32_t bits;
} SecRow;

然后sr.bits。它确实使您的作业时间更长:

SecRow sr = { .fields.section = 2, .fields.row = 3 };