How to define a c struct in Objective-C in its own

2019-09-02 17:03发布

问题:

I'm asking this as two questions because I don't think I can ask one without the other.

In my application, I have a lot of things that are prefixed with "ND" meaning n-dimensional, and I have a method that looks like this in my NDVector class:

angleAtIntersectionWith: (NDVector *) vec 
    inPlaneFirstAxis: (NSUInteger) a1 secondAxis: (NSUInteger) a2

If you're wondering, this method is supposed to find the angle between two vectors in just one plane, meaning by just two of their components, which are indexed by a1 and a2. So, for example. vec1 angleAtIntersectionWith: vec2 inPlanFirstAxis: 0 secondAxis: 2 will find the angle between vec1 and vec2 at their 0 index element and 2 index element (X and Z components).

I wanted to simplify this method to make it look like this:

angleAtIntersectionWith: (NDVector *) vec inPlane: (struct NDPlane *) plane

Where NDPlane should be a structure like this:

struct NDPlane{
    NSUInteger a1;    
    NSUInteger a2;
};

And that's it, that's all it should need. No methods or anything.

I want to keep NDPlane in its own file, so how do I do this? Do I make a simple c header file? If so, am I passing this as struct correctly?

回答1:

Yes, just create a simple .h file that declares the struct. Then import the .h where ever you need it.

However, you don't want the pointer in the argument. C structs are passed by value, not reference. Just like primitive types.

I would also suggest you typedef the struct so you don't need to use struct everywhere you use NDPlane.