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开发者_如何学Go the memory in the array, and failed miserably with a compile error. Can someone explain that as well?
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.
If you have this:
@interface MyClass
{
struct MyStruct foo[5];
}
@end
you can't have a read/write property at all. You can declare a read only property
@property (readonly, assign) struct MyStruct* fooProperty;
which will give you a pointer to the array. However, this is probably bad since it gives the rest of your code internal access to the structure of MyClass. It's proably better to implement the KVC indexed accessors, which you'll have to do manually.
You certainly can treat the array as a property, it will have "assign" behaviour because you can't retain a struct. Essentially you're still totally responsible for the memory allocation of the array.
Another option you have is to replace your struct with an object. Then it works more naturally with the property machinery, and opens up the Foundation collection classes like NSArray to you.
精彩评论