views:

69

answers:

2

I'm learning Objective-C and I'm trying to write a Vector3D class.

In C++ or Java the function I want to implement would look something like this:

Vector3D
{
  Vector3D crossProduct(Vector3D in)
  {
    Vector3D result;
    result = ...  // maths involving this classes variables and the input Vectors variables.
    return result; 
  }
}

Now in objective-c I can't return an object, only an object pointer. Would this be an appropriate place to use autorelease (before returning?). This would enable me to chain the methods on the Vector3D class (since many methods return the object itself) but would this be particularly inefficient as compared to manually allocating and releasing the objects? Are there other commonly used patterns used to return objects in objective-c?

example of operations I'd like to do with the class:

Vector3D * vector3D1 = [[Vector3D alloc] init];
Vector3D * vector3D2 = [[Vector3D alloc] init];
Vector3D * vector3D3 = [vector3D1 cross [ [vector3D2 normalize ] multiply 1.43f]];

Thanks.

+1  A: 

Yes, this is exactly an appropriate usage of autorelease and in fact most people using your code would fully expect that cross, normalize, and multiply return an autoreleased object.

imaginaryboy
+1  A: 

If you create an object, you 'own' it. If you want to relinquish or transfer ownership you must autorelease or release the object. As you can't release an object and then return it, You must autorelease it. Note that this is somewhat stronger than being 'appropriate use'.

The static analyser will warn you if you fail to do this, make sure you have it turned on.

You should not learn the memory management rules from me, you should learn the memory management rules from apple. http://developer.apple.com/library/mac/ipad/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html%23//apple_ref/doc/uid/20000994-BAJHFBGH

Cocoa doesn't have a 2d Point class, instead it makes frequent use of a C struct (NSPoint or CGPoint) instead, maybe because of inefficiencies. Partly because of Apple's example and partly because of fears of inneficiency, you won't very often see a 3dVector class. More commonly you will see a C struct with 4 floats instead. This might also be because it is more useful with OpenGL or OpenCL.

Just a quick point, you say "in objective-c I can't return an object, only an object pointer". This is exactly the same as in Java and C++, and isn't a reason why you would do things differently in objective-c.

mustISignUp
I did read the document you linked to but there's still some other options I could have used other than autorelease, such as passing the 'output' object in and modifying it rather than returning a new object.
CiscoIPPhone
In C++ you can return an object, internally it copies the object but the syntax and semantics are there; Object object; return object: there are no worries over ownership.
CiscoIPPhone