Objective-C/cocoa losing array values

322 views Asked by At

I have multiple arrays, however, they are not retaining their data for use in another method.

Here's how I have it set up (simplified)

.h

NSArray *array;
@property (nonatomic, copy) NSArray *array;
-(void)someMethod:(NSArray*)someArray;
-(void)heresNewMethod;

.m

-(void)someMethod:(NSArray*)someArray
 {
array = [someArray copy];
 }
-(void)heresNewMethod //gets called by method not shown
 {
  NSLog(@"%@", array);
 }
3

There are 3 answers

1
Peter Hosey On BEST ANSWER

One of two things happened:

  • You sent the object a someMethod: message, passing nil (probably without meaning to). A message to nil returns nil, so you assigned nil—as the result of the copy message—to the array instance variable. Even if you had stashed a pointer to an array there previously, you replaced it with nil in your response to this someMethod: message.
  • You never sent the object a someMethod: message. Since instance variables are initialized to nil, and you never put anything different in the array instance variable, it still contains nil.

Sprinkle more NSLog statements in your code to test the first theory. The truth is either one or the other, so confirming the first theory disproves the second, and vice versa.

1
Carl Norum On

Except for the fact that you'll leak whatever was in array every time you call someMethod:, that code should work. What's the problem you see?

1
Bored Astronaut On

The only answer is that the code you provided is not the code your using, and the difference is crucial. I mean, you declare a property which you then don't use, and it's not clear whether you are defining your accessors properly, or if array is also a local which is shadowing your property, or what.

Please post your real code.