开发者

Function to swap pointers in Objective-C

开发者 https://www.devze.com 2023-01-03 16:29 出处:网络
开发者_运维技巧- (void) swapController:(MyViewController*)controller1 with:(MyViewController*)controller2
开发者_运维技巧
- (void) swapController:(MyViewController*)controller1 
                         with:(MyViewController*)controller2
{
    MyViewController *swap = controller2;
    controller2 = controller1;
    controller1 = swap;
}

Looks like this doesn't work because I'm not passing references. How to do it anyway?


You can do this by passing in pointers to the pointers you want to change:

- (void)swapController:(MyViewController**)controller1 with:(MyViewController**)controller2
{
    MyViewController* swap = *controller2;
    *controller2 = *controller1;
    *controller1 = swap;
}


Not looking for this as an opposing answer here, but rather to complement @Huw's answer.

On implementing his swapController:with: method above, I noticed some issues with ARC and with primitives. ARC will take issue if you're passing a strong id* to an id* ( which it will designate as autoreleased id and other fun warnings).

If you're anything like me, well, one fine day you'll be swapping pointers back and forth in objc and one of those values will be a primitive data type.

If you do end up doing something like that, here's a little helper (like I said earlier) to complement the above answer:

 void swapObjcPointerWithC ( void** ptrA, void** ptrB ) {

     void *temp = *ptrA;
     *ptrA = *ptrB;
     *ptrB = temp;

 }

 ...
 // Later on

 id objA;
 int anInt = 10;
 swapObjcPointerWithC ( (void*)&objA, (void*)&anInt );

There you go. My two cents. Note: also works will nil pointers apparently.

0

精彩评论

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