开发者

Swapping objects. Cant get my head around it

Ok if I have 3 objects.

ObjectType *objX;
Obj开发者_如何学运维ectType *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


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).


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜