Search code examples
objective-carraysdeclared-property

Using a C array as a property


I need to declare a property for a C array of a custom struct type.

Can someone explain what I should be doing with this C array as far as property declarations? Should I not be using a property declaration at all?

I tried memset()ing the memory in the array, and failed miserably with a compile error. Can someone explain that as well?


Solution

  • This answer doesn't really solve your problem, it just explains why your approach didn't work.

    In C you cannot return array types from functions. This is simply a limitation of the language (intentional or unintentional I don't know). By extension, in Objective-C you cannot return array types from methods. This also means that you can't use array types as properties, because the compiler is unable to synthesize a method that returns an array type.

    C arrays are automatically converted into pointer types when used in an expression, so you can follow @Graham's advice and use pointers instead. The downside to this approach is that you must know exactly how many elements are in the array so that you don't accidentally read past the end of the it. If the number of elements is fixed and known at compile-time, this is probably the way to go (if you want to avoid NSArray for whatever reason).

    It's difficult to answer whymemset failed to compile without actually seeing how you used it, but generally speaking this is how it can be used:

    MyStruct someStructs[10];
    
    memset(someStructs, 0, sizeof someStructs);
    

    Alternatively, it is possible to return structs from functions/methods, even if they contain arrays. Theoretically speaking, you could create a struct containing an array of MyStruct and use this new struct type as the property type. Practically speaking this isn't a good idea since it just adds a layer of complexity.