开发者

Objective-C: instance variable as a parameter, but after method call instance variable is empty

开发者 https://www.devze.com 2023-02-27 10:12 出处:网络
I do some iOS programming stuff and I have a UIViewController with a NSMutableArray: @property (nonatomic, retain) NSMutableArray* mutableTestArray;

I do some iOS programming stuff and I have a UIViewController with a NSMutableArray:

@property (nonatomic, retain) NSMutableArray* mutableTestArray;
...
@synthesize mutableTestArray;

In viewDidLoad I want to call a method which is inside the implementation of this UIViewController:

//- (void)aTestMethod:(NSMutableArray *)myMutableTestArray;
[self aTestMethod:self.mutableTestArray];

So I call the method with a NSMutableArray which is an instance variable of the UIViewController. Inside this method, I do this:

myMutableTestArray = [NSMutableArray arrayWithCapacity:100];
//... looping & generating some objects and adding them to the array:
[myMutableTestArray adObject:myObject];

Now, I debug it and inside the method myMutableTestArray is fine. There are all objects inside the array. But leaving this method the instance variable mutableTestArray is empty.

So, where 开发者_Python百科is the problem? Anyone an idea? Note: I know I can access the instance variable with self.mutableTestArray and then everything will be okay, instead using it as a parameter, but I want to know what's wrong with my code.

Thank you in advance & Best Regards.


Parameters are passed by value in Objective-C. Thus, you are creating a copy of a pointer to the object and passing that into the method. When you do myParam = ... new object ...; that resets the copy to point to a new location, but has no effect on the original copy in the caller.

(To reiterate -- you are copying the pointer, not copying the object.)

To solve, declare your test method as returning an object:

- (NSMutableArray *)aTestMethod;

Then, you can simply:

self.mutableTestArray = [whateverObject aTestMethod];

(Since you aren't actually using the value passed in in the first place, there is no need for a parameter at all).


By your command

myMutableTestArray = [NSMutableArray arrayWithCapacity:100];

you are creating new allocation of mutableTestArray. So passing mutableTestArray as parameter to aTestMethod:

[self aTestMethod:self.mutableTestArray];

is useless because you override its value immediately when create this array inside your aTestMethod.

Try to create your array before passing it to your method (where you will fill it with data).


Remember that parameters are transmitted by value, so in aTestMethod: you are modifying not the original pointer but a copy of it! For this to work, you should pass the address of the pointer as in

self aTestMethod:&(self.mutableArray)

then the prototype of the method should be

-(void)aTestMethod:(NSMutableArray **)myArray

and in the code of it you should used *myArray as in

*myArray = [[NSMutableArray alloc] init];

Yours, JB

0

精彩评论

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