Re: [NEWBIE] Right way to make lightweight class/structs?
Re: [NEWBIE] Right way to make lightweight class/structs?
- Subject: Re: [NEWBIE] Right way to make lightweight class/structs?
- From: David Trevas <email@hidden>
- Date: Fri, 7 Sep 2001 01:47:55 -0500
>
I need to make some lightweight classes. The first one I'm encountering
>
is my Vec3f class, which in C terms is just
>
>
typedef struct
>
{
>
float x, y, z;
>
} Vec3f;
>
>
I'm tentatively just implementing everything in regular C
>
interfaces, and that's been successful so far.
>
There are C structures used in Cocoa. Look as NSRect, NSSize, and
NSRange to name a few. Structs are just fine for simple storage, but it
seems that for vectors, you'd want to be able to add, subtract,
normalize, take scalar, dot and cross products and do matrix
multiplication (for which you'd need to develop a Matrix class). A
vector is therefore much more than a storage class and probably deserves
a true class.
- (void) setXYZ: (float *)inputVector
{
x = inputVector[0]; y = inputVector[1]; z = inputVector[2];
}
- (float *) xyz
{
static float temp[3];
temp[0] = x; temp[1] = y; temp[2] = z;
return temp;
}
I don't want to make this a class because accessing everything through a
get/set interface doesn't make much sense and would be grossly
cumbersome.
Do you find the previous accessor methods grossly cumbersome? This is a
very quick and dirty approach to your problem, but I'll bet that using
an NSArray instead of x, y and z is much truer to the Cocoa spirit.
That may get a little more cumbersome, but you get added safety (if
someone put a 2D vector in the setXYZ: method above, you could be lucky
and get an explicit out-of-range message or unlucky and get garbage that
may be difficult to root out) and you don't have to mess with the static
array in xyz.
Of course, you can always use the @public directive to expose x, y and z
for anyone to read and write. That's quite frowned upon.
Here's a method for the Vec3f class that does scalar multiplication and
the code would read:
vector2 = [vector1 multipliedByScalar: 3.453];
That's almost starting to look like plain English!
- (void) multipliedByScalar: (float) factor
{
x *= factor; y *= factor; z *= factor;
}
>
When allocating memory for a chunk of Vec3fs, should I just use good old
>
malloc() or is there an Obj-C equivalent to C++'s "new"? I can't use
>
"alloc" since this isn't an NSObject.
That's one good argument for making it a subclass of NSObject. You get
easy allocation and memory management without doing anything (if you are
using the statically-typed floats as your ivars, if you wanted to use an
NSArray for storage you'd have to write a simple init... function that
creates the array and a dealloc that releases it.)
>
Any and all advice appreciated.
I hope this helps.
Dave