2011-03-09 70 views
0

我一直在尝试几个小时试图让这个工作,但我似乎无法做到。用户按下一个按钮,该按钮在HandlingPalettes中调用“newPalette”,然后推入SingleView。这里的所有revelant代码我有:在类之间传递NSMutableArray的问题

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

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

非常感谢。

+0

它应该怎么做? – Max 2011-03-09 04:00:15

+0

为什么这是downvoted? – KingofBliss 2011-03-09 04:03:26

+0

它应该传递数组,以便两个区域的计数相同。 – Andrew 2011-03-09 04:09:29

回答

4

您正在为HandlingPalettes类创建不同的实例。你应该使用单例来做到这一点。

HandlingPalettes.m中的handlingPalettes和SingleView中的handlingPalettes总是不同的。所以使用单例类,或使用appDelegate在不同的类中访问。

+0

+ 1,是的,让不同类别的对象重新活化数组。 – Ishu 2011-03-09 04:21:13

+0

我不明白,你能解释一下吗? – Andrew 2011-03-09 04:24:03

+0

您正在为类handlingPalettes创建一个新实例,这将为handlingPalettes.color分配一个新的内存位置,但旧的实例将位于其他一些内存位置。所以它产生不同的值 – KingofBliss 2011-03-09 05:12:11

0

你需要这个

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

替换该行HandlingPalettes.m

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

而且你需要更改这里

@interface SingleView : UIViewController { 

} 

HandlingPalettes *handlingPalettes; //not here 

@end 

正确

@interface SingleView : UIViewController { 

    HandlingPalettes *handlingPalettes;  

    } 



    @end 

编辑:

因为它重新初始化array.so,你需要你在同一个类中创建这个数组或者在appDelegate类中创建这个数组。因为应用程序委托类不会对其进行调整。

+0

不幸的是,在做出这些更改后,它返回了相同的结果。 – Andrew 2011-03-09 04:08:45