views:

45

answers:

2

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!

+1  A: 
  • 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:

static NSArray *fruits;

+ (NSArray *)myFruits {
  if (!fruits) {
    fruits = [NSArray arrayWithObjects:[NSNumber numberWithInt:enumValue], nil];
  }
}
vodkhang
This is the solution I will use, thank you!
Richard J. Ross III
It's not really accurate to say that you can't use C arrays in Objective-C. They're used in several different APIs in Cocoa itself. It's just that they're not useful for objects and awkward in any language.
Chuck
No reason you can't use C code, including a C array, in Objective-C. NSArrays are often better, but for a simple, static array of int values (and enums are just int values), a C array might be better.
mipadi
Uhm, I didn't say that you can't use C arrays in Objective-C. I just meant that his code is not Objective-C code, and we can return a NSArray but we cannot return a C array (but yeah, we can return a pointer). But I will clarify it
vodkhang
+1  A: 

You have to declare the method as returning a pointer to a Fruit, rather than an array. You can do so like this:

@implementation FruitTest

static Fruit fruits[] = {FRUIT_APPLE, FRUIT_BANANA};

+(Fruit *) fruits
{
    return fruits;
} 

@end
mipadi
The problem with this is that, without some further information (like a sentinel value at the end of the array), there's no way for the caller to know the size of the array that the pointer refers to.
David Gelhar