开发者

argument pass by reference in obj-c

开发者 https://www.devze.com 2023-03-02 01:11 出处:网络
I just did one research, but I am having a problem - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

I just did one research, but I am having a problem

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  int r1=40,r2=5;
  swap(r1,r2);

  NSLog(@" temp is %d",r1);
}

void swap(int r1, int r2)
{
  NSLog(@" m i 1st");
  int temp;
  temp=r1;
 开发者_StackOverflow r1=r2;
  r2=temp;

  NSLog(@" temp is %d",r1);
}

I am getting conflicting type of swap; is this correct way of doing this? Thanks!


If you want r1 and r2 to be swapped, you either have to pass pointers, or use C++ references. Note that using C++ references will require you to dive into Objective-C++, which in this case means naming your file .mm instead of .m.

void swap_with_pointers(int *r1, int *r2)
{
  int temp;
  temp = *r1;
  *r1 = *r2;
  *r2 = temp;
}

void swap_with_references(int &r1, int &r2)
{
  int temp;
  temp = r1;
  r1 = r2
  r2 = temp;
}

Then, use one of your implementations like so:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  int x = 3;
  int y = 4;
  swap_with_pointer(&x, &y); // swap_with_references(x,y);
  printf("x = %d, y = %d", x, y);
  return 0;
}

The output, either way:

x = 4, y = 3

0

精彩评论

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