将struct literal传递给ObjC方法

时间:2015-01-17 11:06:11

标签: objective-c struct

a talk at the @Scale 2014 conference(大约32:30)期间,Facebook展示了他们的声明式UI方法的实现。可以找到更详细的演讲版本的幻灯片here

基本上他们提出了这样的函数调用(我在演讲的例子中创建了自己的简化示例):

[CPInsetComponent
  newWithStyle:{
    .margin = 15
  }
];

我的问题是:这是有效的ObjC代码吗?我试着自己实现这个

typedef struct {
  uint margin;
} CPInsetComponentStyle;


@interface CPInsetComponent : NSObject

+ (SomeOtherStruct) newWithStyle:(CPInsetComponentStyle)style;

@end

但我仍然在newWithStyle:{行上收到“预期表达式”错误。你能给我一个暗示方法声明的样子吗?

2 个答案:

答案 0 :(得分:3)

不,那是无效的Objective-C代码。结构类型的C99复合文字如下所示:

(TheStructType) { .field1 = initializer1, .field2 = initializer2 }

字段标识符是可选的。

我可以想象他们呈现的代码实际上是Objective-C ++。在C ++ 11中,如果满足某些条件,编译器可以向构造函数插入隐式调用,并采用初始化列表;因此,通常只能将初始化列表传递给函数。

答案 1 :(得分:2)

编译器可能不知道您的文字结构声明是否是正确的类型。对于复合文字,您需要在括号中提供类型,后跟括号括起的初始化列表。

[CPInsetComponent newWithStyle:(CPInsetComponentStyle){
  .margin = 15
}];
相关问题