Andrew
Andrew

Reputation: 16051

Problem passing NSMutableArray between classes

I've been trying for hours to try and get this to work, but I can't seem to do it. The user pressed a button, which calls 'newPalette' in HandlingPalettes, and then pushes in SingleView. Here's all the revelant code I have:

HandlingPalettes.h:

@interface HandlingPalettes : UIViewController {

NSMutableArray *navBarColour;

}

@property (nonatomic, retain) NSMutableArray *navBarColour;

-(void)newPalette;

@end

HandlingPalettes.m:

#import "HandlingPalettes.h"
#import "SingleView.h"



@implementation HandlingPalettes

@synthesize navBarColour;


-(void)newPalette {

    UIColor *colourOfNavBar = [UIColor colorWithHue:0 saturation:0 brightness:0.25 alpha:1];
    if (navBarColour == nil) {
        navBarColour = [[NSMutableArray alloc] initWithObjects:colourOfNavBar, nil];
        currentPalette = 0;
    }
    else {
        [navBarColour addObject:colourOfNavBar];
        currentPalette = navBarColour.count-1;
    }

    NSLog(@"Number: %i", navBarColour.count);

}

- (void)dealloc {
    [super dealloc];
}
@end

SingleView.h:

#import "HandlingPalettes.h"


@interface SingleView : UIViewController {

}

HandlingPalettes *handlingPalettes;

@end

SingleView.m:

#import "SingleView.h"

@implementation SingleView


- (void)viewDidLoad {

    handlingPalettes = [[HandlingPalettes alloc] init];
    NSLog(@"Second number: %i", handlingPalettes.navBarColour.count);
    [super viewDidLoad];

}

- (void)dealloc {
    [handlingPalettes release];
    [super dealloc];
}


@end

The problem I have is that NSLog returns:

Number: 1 Second Number: 0

And then going back to the first view and pressing the button again..

Number: 2 Second Number: 0

And again..

Number 3: Second Number: 0

Can somebody help me and explain why this isn't working?

Thanks so much.

Upvotes: 0

Views: 639

Answers (2)

Ishu
Ishu

Reputation: 12787

you need to replace this line in HandlingPalettes.m

navBarColour = [[NSMutableArray alloc] initWithObjects:colourOfNavBar, nil];

with this

self.navBarColour = [[NSMutableArray alloc] initWithObjects:colourOfNavBar, nil];

And you need change here

@interface SingleView : UIViewController {

}

HandlingPalettes *handlingPalettes; //not here

@end

correct

 @interface SingleView : UIViewController {

   HandlingPalettes *handlingPalettes;    

    }



    @end

Edit:

Because it reinitialize the array.so you need either you make this array in same class or make in appDelegate class. because app delegate class not reintialize it.

Upvotes: 0

KingofBliss
KingofBliss

Reputation: 15115

You are creating a different instance to HandlingPalettes class. You should use singleton to do so.

handlingPalettes in handlingPalettes.m and handlingPalettes in SingleView are always different. So use singleton class, or use appDelegate to access in different class.

Upvotes: 4

Related Questions