我在RootViewController中初始化了一个数组,并将一个方法添加到数组中。我在SecondViewController中创建了一个RootViewController对象。该方法运行(输出消息),但它不向数组添加任何内容,并且数组似乎为空。代码在下面,有什么建议吗?
RootViewController.h
#import "RootViewController.h"
#import "SecondViewController.h"
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
myArray2 = [[NSMutableArray alloc] init];
NSLog(@"View was loaded");
}
-(void)addToArray2{
NSLog(@"Array triggered from SecondViewController");
[myArray2 addObject:@"Test"];
[self showArray2];
}
-(void)showArray2{
NSLog(@"Array Count: %d", [myArray2 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 "RootViewController.h"
@implementation SecondViewController
-(IBAction)addToArray{
RootViewController *object = [[RootViewController alloc] init];
[object addToArray2];
}
-(IBAction)switchBack{
[self dismissModalViewControllerAnimated:YES];
}
EDIT *************
使用Matt的代码我收到以下错误:
“'RootViewController'之前的预期说明符限定符列表”
答案 0 :(得分:0)
你在这里缺少一些非常重要的基础知识。如果在SecondViewController中分配新的RootViewController,它与用于创建SecondViewController的实例不同,因此它不会引用要添加对象的数组。你想做什么是行不通的。您必须在SecondViewController中为RootViewController创建一个ivar,然后在第二个视图中访问它。像这样:
-(IBAction)switchViews{
SecondViewController *screen = [[SecondViewController alloc]
initWithNibName:nil bundle:nil];
screen.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[screen setRootViewController:self];
[self presentModalViewController:screen animated:YES];
[screen release];
}
你的ivar需要在SecondViewController.h中声明:
@property (nonatomic, retain) RootViewController *rootViewController;
然后在.m
中合成然后,您可以从SecondViewController中访问ivar:
-(IBAction)addToArray{
[[self rootViewController] addToArray2];
}