views:

97

answers:

4

I have an ObjC object defined as follows

@interface Fruit : NSObject
{
    int fruitsinbranch[4];
}
@property (readonly) int fruitsinbranch[4];
@end

And then in the implementations I have the usual

@synthesize fruitsinbranch[4];

It does not work. What's the right way of doing it?

(And no, I am not asking for other ways to do stuff, like NSArray etc... I want an answer to the question I posed).

UPDATE: my solution is lame but it works. I created the method

-(int) fruitsinbranch:(int) i

That gave a solution close enough to what I wanted.

A: 

Unfortunately, it's not supported by Objective-C to have an C-array-valued property.

Yuji
A: 

Specifying readonly and then asking it to synthesize a setter and getter (specifically the setter) doesn't make sense, though it should work. And according to this objective c property document, you'll at least get a compiler warning when explicitly setting a setter on an object that is readonly.

Perhaps you could try explicitly setting them with setter= and getter=? I know this defies your original question, but you might raise an error if your issue is somewhere else.

Nick
+2  A: 

It isn't meaningful to specify a setter for a C array — there isn't even such a concept as "setting an array" in C. You can initialize the array, and you can access its elements, but you cannot set the array itself.

As for a getter, I can't think of any reason it couldn't work, but the runtime just doesn't support C arrays as properties. It just wasn't built in — probably because arrays don't really work like other types in C, such as the previously mentioned fact that there is no such thing as setting them.

The closest you can get is to specify a readonly int* property that you malloc in your initializer.

Chuck
Hm, what would a hypothetical synthesized getter do as pass-by-value doesn't work? Decay to a pointer?
Georg Fritzsche
Yes, that's what I'm thinking — it would have to decay to a pointer, but that would be consistent with how any function returning an array works.
Chuck
Can we write a Objective-C method which returns an `int[4]`, to start with?
Yuji
@Yuji: No, as you can't pass them by value and decay-to-pointer is not in the language for return types. You can only return pointers or e.g. a pointer-to-array.
Georg Fritzsche
+2  A: 

The closest thing you can get is to use an int* property and not synthesize the getter:

 @interface Fruit : NSObject {
     int fruitsinbranch[4];
 }
 @property (readonly) int* fruitsinbranch;
 - (int *)fruitsinbranch { return fruitsinbranch; }
Georg Fritzsche
No, no, you shouldn't give him the alternative. He wanted an answer to the question he posted! :)
Yuji
@Yuji: Hey, i didn't throw an `NSArray` in :) Without alternative we can only say *"no way"*.
Georg Fritzsche