BigK
BigK

Reputation: 43

Why isn't NSMutableArray working?

I have a NSMutableArray of a class, and in other class I'd like to initialize it and add various objects. But the problem is that the NSMutableArray isn't retaining the elements. I have the following code:

 -(void)viewDidLoad
  {
    [super viewDidLoad];
    MyStops *myStops = [self.storyboard instantiateViewControllerWithIdentifier:@"My Stops"];
    myStops.myStopsMArray = [[NSMutableArray alloc] init];
  }

And this one:

- (void) addToFavourites:(id)sender 
  {
    UITapGestureRecognizer *gesture = (UITapGestureRecognizer *) sender;

    NSInteger tag = gesture.view.tag;

    UITableViewCell *cell = [stopsTable dequeueReusableCellWithIdentifier:@"cell"];

    MyStops *myStops = [self.storyboard instantiateViewControllerWithIdentifier:@"Mis Paradas"];

    [myStops.myStopsMArray addObject:[stopsArray objectAtIndex:tag]];
 }

And in the other file I have the NSMutableArray declared and synthesized:

//Header file
@property (nonatomic, retain) NSMutableArray *myStopsMArray;

//Implementation file
@synthesize myStopsMArray;

Can you tell me please what I'm doing wrong? Thanks!

Upvotes: 0

Views: 55

Answers (2)

arturdev
arturdev

Reputation: 11039

instantiateViewControllerWithIdentifier creates and returns NEW INSTANCE every time! So you must have a direct pointer to that view controller. In the header file of your current class make a property like:

@property (strong, nonatomic) MyStops *myStopsVC;

NOTE: Change strong to weak if your current ViewController already presented from MyStops. But if you're going to push/present MyStops from this vc, then keep it as strong pointer.

Upvotes: 1

AliSoftware
AliSoftware

Reputation: 32681

You have two distinct instances of your MyStops ViewController, that's why.

In you viewDidLoad, you create a MyStops ViewController then alloc/init its "myStopsMArray" NSMutableArray.

But in you addToFavorites method, you create another, different and brand new MyStops instance — for which you didn't alloc/init you myStopsMArray property. Hence in that method, myStops.myStopsMArray is still nil.

Upvotes: 0

Related Questions