views:

58

answers:

2

Ok if I have 3 objects.

ObjectType *objX;
ObjectType *objY;
ObjectType *tempObjHolder;

objX = [[alloc ObjectType] init];
objY = [[alloc ObjectType] init];

// some code to change values in the objX and objY

tempObjHolder = objX;
objX = objY;
objY = tempObjHolder;

Am i swapping the objects ok. Or am I confused to how this works. Do i end up making them all point to one object?

What I am trying to do is make ObjX equal to what objY is then make ObjY equal to what ObjX was.

Thanks -Code

A: 

There's a big difference between "equal to" and "pointer to the same." Your example properly swaps them around so the objects at pointers x and y have swapped positions, but are still distinct.

However, because you haven't nil'd out tempObjHolder in your example, both tempObjHolder and objY both point to the same object (that which was originally assigned to objX).

Also, as thyrgle pointed out, you're missing the pointer in your declarations:

ObjectType * someObj;
Joshua Nozzi
Joshua at what stage should the tempObjHolder be set to nil?
Code
I tested this out, and objX and ObjY are the same object at the end. Because when i try change objY the result appears in both objX and objY.
Code
You would nil tempObjHolder as the last step. This is normally not done, as it is tempObjHolder should be declared so that it goes out of scope when you are done with it.
BillThor
+1  A: 

That is the generic way to swap any two variables, and yes, you're doing it correctly (though the object-creation code before it won't even compile due to the fact that objects must be pointers and alloc is not an object).

Chuck