NSMutableArray&多视图

时间:2010-06-11 21:36:47

标签: iphone objective-c nsmutablearray

我正在尝试编写一个需要在不同视图中访问和修改NSMutableArray的应用程序。
MainViewController显示一个表格,用于从NSMutableArray获取信息。 SecondaryViewController用于将对象添加到数组中 如何在不将其声明为全局变量的情况下进行此操作?

修改
这是我到目前为止: (MainView .m)

#import "arrayTestViewController.h"

@implementation arrayTestViewController

-(void)viewDidLoad{
    myArray = [[NSMutableArray alloc] init];

}
-(IBAction)showArray{
    NSLog(@"Array Count: %d",[myArray count]);
}   

-(IBAction)addToArray{

[myArray addObject:@"Test"];
[myArray addObject:@"Test2"];
NSLog(@"Array Count: %d", [myArray count]);

}

-(IBAction)switchViews{
    SecondViewController *screen = [[SecondViewController alloc] initWithNibName:nil bundle:nil];
    screen.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentModalViewController:screen animated:YES];
    [screen release];
}

(SecondViewController .m)

#import "SecondViewController.h"
#import "arrayTestViewController.h"

@implementation SecondViewController



-(IBAction)addToArray{
    // Trying to make a method add to myArray in the Main, but not sure of the syntax
    // I'm guessing localizing another array and pointing to the original?

}

-(IBAction)switchBack{
    [self dismissModalViewControllerAnimated:YES];
}

5 个答案:

答案 0 :(得分:0)

您应该查看依赖注入模式 - http://en.wikipedia.org/wiki/Dependency_injection

初始化SecondaryViewController时,可以将引用(指针)传递给NSMutableArray,并将其保存在本地实例变量中。然后在任何时候,当SecondaryViewController需要访问数组时,它可以使用它的引用。

答案 1 :(得分:0)

将数组作为参数传递给SecondaryViewController的构造函数,从而允许SecondaryViewController向其添加对象,当MainViewController再次可见时将显示的对象,并重新加载表数据。

答案 2 :(得分:0)

如何显示SecondaryViewController?如果您愿意,可以在SecondaryViewController标头中定义一个属性,如下所示:

{
NSMutableArray *theArray;
}

@property (nonatomic, retain) NSMutableArray *theArray;

然后你必须在@implementation

下面@synthesise
@synthesise theArray

在您创建SecondaryArrayController之后的MainViewController中,您可以执行

theSecondaryViewController.theArray =theArrayWhichYouHaveCreated;

现在两个对象都有一个指向同一对象的指针。读入一个,写入另一个!我没有测试过这段代码,但它应该可行。如果没有,请发表评论!

答案 3 :(得分:0)

您必须声明NSMutableArray并在TestAppDelegate.h中设置属性 例如:

@interface TestAppDelegate : NSObject  {
    NSMutableArray *arrayList;
}
@property (nonatomic, retain) NSMutableArray *arrayList;
@end

在主类中,您必须为arrayList;

设置@synthesize

如果你想在arrayList SecondViewController中添加一个对象,只需编写以下代码


TestAppDelegate *appDelegate = (TestAppDelegate*)[[UIApplication sharedApplication] delegate];
[appDelegate.arrayList addObject:object];

您可以从任何类(您在应用程序中使用)中访问此数组;


TestAppDelegate *appDelegate = (TestAppDelegate*)[[UIApplication sharedApplication] delegate];
1. NSMutableArray *array = [appDelegate.arrayList retain]; 

or

2. NSMutableDictionary *dictionary = [appDelegate.arrayList objectAtIndex:index];

我认为它会对你有帮助......

感谢。

答案 4 :(得分:-1)

让一个控制器负责阵列并且对阵列的所有访问权都通过该控制器。例如,为MainViewController提供对SecondaryViewController的引用,并将SecondaryViewController设置为表的数据源。