简体   繁体   English

通过引用方法传递变量(Objective-C Iphone SDK)

[英]Pass variable by reference to method (Objective-C Iphone SDK)

Hi :) This is messing me up quite the bit... 嗨:)这让我很困惑...

Say I have this method: 说我有这种方法:

-(void) initEvent:(NSMutableArray*) Day day:(float)DayNum
{
   //[Day addObject:[[[LifeEvent alloc] init] initVars:100]];
   [Day addObject:@"Hello"];
   [Day addObject:@"there :)"];
}

I call that method in a small loop: 我在一个小循环中调用该方法:

for (int i = 0; i < 7; i++)
   {
      NSMutableArray * DayTMP = [[NSMutableArray alloc] init];
      [self initEvent:DayTMP day:i];
   }

Theoretically, this should pass DayTMP to the function, and add data to that variable. 从理论上讲,这应该将DayTMP传递给函数,并将数据添加到该变量。 Not the case, instead, it creates a copy of DayTMP, adds data to that value, and drops it. 并非如此,而是创建DayTMP的副本,将数据添加到该值,然后删除它。 DayTMP never gets modified! DayTMP永远不会被修改!

I need to know how to pass values to functions as pointers, not copies, so that DayTMP is modified. 我需要知道如何将值作为指针而不是副本传递给函数,以便修改DayTMP。

Actually what you are doing here is that you are creating 7 NSMutableArray type objects and the same variable name DayTMP is used for all of them ....... so loose the access of all 6 of them and and you only can access the last one because in every itteration of the loop DayTMP is pointing to new location ....... so to achieve what you want you should do following... 实际上,您在这里要做的是创建7个NSMutableArray类型的对象,并且所有这些对象都使用相同的变量名DayTMP .......因此,松开了对所有6个对象的访问,您只能访问最后一个是因为DayTMP在循环的每个发信号中都指向新位置.......因此,要实现您想要的目标,您应该执行以下操作...

  NSMutableArray * DayTMP = [[NSMutableArray alloc] init];
  for (int i = 0; i < 7; i++)
  {
      [self initEvent:DayTMP day:i];
  }

Normally your code should work fine except that you never release DayTMP creating a memory leak. 通常,您的代码应该可以正常工作,除非您从不释放DayTMP从而造成内存泄漏。 You are indeed passing a pointer to an NSMutableArray : (NSMutableArray*) . 您确实在传递指向NSMutableArray的指针: (NSMutableArray*)

You "init" DayTMP inside the loop!!! 您在循环内“初始化” DayTMP!

that means you create (and never release!) the same object many time, overriding it every time, so you kill the old one each time, and you get just the last one: it's a memory error 这意味着您多次创建(并且永远不会释放!)同一对象,每次都覆盖它,因此您每次都杀死一个旧对象,而您得到的只是最后一个对象:这是内存错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM