在类之间传递NSMutableArray的问题

时间:2011-03-09 03:52:51

标签: iphone objective-c xcode nsmutablearray

我已经尝试了几个小时试图让它工作,但我似乎无法做到这一点。用户按下了一个按钮,在HandlingPalettes中调用'newPalette',然后按下SingleView。这是我所拥有的所有重要代码:

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

我遇到的问题是NSLog返回:

数量:1 第二个数字:0

然后回到第一个视图并再次按下按钮..

数量:2 第二个数字:0

再次..

3号: 第二个数字:0

有人可以帮助我并解释为什么这不起作用吗?

非常感谢。

2 个答案:

答案 0 :(得分:4)

您正在为HandlingPalettes类创建不同的实例。你应该使用单身人士来做这件事。

处理在SingleView中的Palettes.m和handlingPalettes中的handlePalettes总是不同的。所以使用singleton类,或使用appDelegate访问不同的类。

答案 1 :(得分:0)

您需要在HandlingPalettes.m

中替换此行
navBarColour = [[NSMutableArray alloc] initWithObjects:colourOfNavBar, nil];

用这个

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

你需要在这里改变

@interface SingleView : UIViewController {

}

HandlingPalettes *handlingPalettes; //not here

@end

正确

 @interface SingleView : UIViewController {

   HandlingPalettes *handlingPalettes;    

    }



    @end

编辑:

因为它重新初始化了数组。所以你需要在同一个类中创建这个数组,或者在appDelegate类中创建。因为app委托类没有重新加入它。

相关问题