Objective-C 从方法返回枚举数组
我的 Objective-C 代码中有一个与此类似的枚举:
typedef enum {
FRUIT_APPLE = 1,
FRUIT_PEAR = 2,
FRUIT_BANANA = 3,
// etc.
} Fruit
我需要能够在方法中返回这些数组,如下所示:
@implementation FruitTest
static Fruit fruits[] = {FRUIT_APPLE, FRUIT_BANANA};
+(Fruit[]) fruits
{
return fruits;
}
@end
但是,这会生成编译错误:
#1 'fruits' declared as method returning an array
#2 Incompatible types in return
关于如何解决此问题的任何想法? 谢谢!
I have an enum in my objective-C code similar to this:
typedef enum {
FRUIT_APPLE = 1,
FRUIT_PEAR = 2,
FRUIT_BANANA = 3,
// etc.
} Fruit
I need to be able to return an array of these in a method, something like this:
@implementation FruitTest
static Fruit fruits[] = {FRUIT_APPLE, FRUIT_BANANA};
+(Fruit[]) fruits
{
return fruits;
}
@end
However, this generates a compile error:
#1 'fruits' declared as method returning an array
#2 Incompatible types in return
Any ideas on how to solve this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 C 代码,您不能像当前代码那样直接返回数组,而是需要返回指针。在obj-c中,你还可以使用NSArray,你可以返回它。
但是,您不能创建枚举数组,也不能创建 int 或 NSInteger 数组,您需要像
fruits = [NSArray arrayWithObjects:[NSNumber numberWithInt:enumValue]];
您的代码应该如下所示:
With C Code, you cannot return an array directly like your current code but you need to return a pointer. In obj-c, you can also use NSArray, which you can return.
However, you cannot make an array of enum, neither an array of int or NSInteger, you need to do like
fruits = [NSArray arrayWithObjects:[NSNumber numberWithInt:enumValue]];
Your code should look like:
您必须将该方法声明为返回一个指向
Fruit
的指针,而不是一个数组。你可以这样做:You have to declare the method as returning a pointer to a
Fruit
, rather than an array. You can do so like this: