开发者

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

开发者 https://www.devze.com 2023-02-13 03:50 出处:网络
Hi :) This is messing me up quite the bit... Say I have this method: -(void) initEvent:(NSMutableArray*) Day day:(float)DayNum

Hi :) This is messing me up quite the bit...

Say I have this method:

-(void) initEvent:(NSMutableArray*) Day day:(float)DayNum
{
   //[Day addObject:[[[Li开发者_StackOverflow中文版feEvent 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. Not the case, instead, it creates a copy of DayTMP, adds data to that value, and drops it. DayTMP never gets modified!

I need to know how to pass values to functions as pointers, not copies, so that DayTMP is modified.


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

  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. You are indeed passing a pointer to an NSMutableArray : (NSMutableArray*).


You "init" DayTMP inside the loop!!!

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

0

精彩评论

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