switching two pointers problems

Discussion in 'iOS Programming' started by ycyclop, Jun 23, 2009.

  1. ycyclop macrumors newbie

    Jun 23, 2009
    Hi all,
    I'm new to this objective C and I thought I understood what I was doing, but apparently not. here is a simplified sample of my problem:

    I have two objects:

    MyObj* obj1 = [[MyObj alloc] initWithMyData:X];
    MyObj* obj2 = [[MyObj alloc] initWithMyData:Y];

    I wanted to switch the content of the two items with the following simple code:

    MyObj* temp = obj1;
    obj1 = obj2;
    obj2 = temp;

    so when I look at the address, obj1 now hold the address of what was previously obj2 and obj2 hold the address of obj1
    looks like what I wanted right? NO
    the data inside obj1 is the same data as before. and same for obj2:

    obj1.data is still X as initilized with but address of what was obj2
    obj2.data is still Y as initilized with but address of what was obj1

    so how come when I replaced the pointers the data stayed the same?

    Thank you in advance for any help
  2. dejo Moderator


    Staff Member

    Sep 2, 2004
    The Centennial State
    Wow, that's strange. I have very similar code for switching NSStrings and it does work. I can't understand how yours doesn't.
  3. eddietr macrumors 6502a

    Oct 29, 2006
    Are you sure you didn't make a mistake in looking at the content of these objects?

    Maybe you should post a concrete example with the actual source code showing that you found "X" in one case and "Y" in the other. For example print the value X in one object before and after the swap.

Share This Page