从另一个视图控制器
FirstViewController.h访问变量:从另一个视图控制器
#import <UIKit/UIKit.h>
@interface FirstViewController : UIViewController
{
NSArray *listData;
}
-(IBAction) GoToInsert: (id) sender;
@property (nonatomic, retain) NSArray *listData;
@end
FirstViewController.m:
-(IBAction) upisiRezultat:(id)sender
{
SecondViewController *secondView = [[SecondViewController alloc] initWithNibName: nil bundle: nil];
[self presentModalViewController: secondView animated: NO];
[secondView release];
}
- (void)viewDidLoad
{NSArray *array = [[NSArray alloc] initWithObjects:@"236", @"46",
@"147", @"8", @"56", @"69", @"114", @"2",
@"96", @"518", @"2", @"54", @"236", nil];
self.listData = array;
[array release];
[super viewDidLoad];
}
SecondViewontroller.h
@interface SecondViewController : UIViewController {
}
-(IBAction) insert;
@end
SecondViewontroller.m
-(IBAction) insert
{
/* Here should be the code to insert some number in listData from FirstViewController */
}
所以,当应用程序加载它加载FirstViewController.xib并在屏幕上显示的listData阵列,当我点击按钮“去插入”另一种观点被加载(SecondViewController.xib )与“插入”按钮,它应该添加一些数字到数组中,并在第一个视图上显示新的数组。
如何做到这一点?
您可以通过self.parentViewController
访问父视图控制器。因此这些方针的东西(指我没有测试过这一点 - 你应该)应该工作:
FirstViewController *firstViewController = self.parentViewController;
NSMutableArray *newArray = [[NSMutableArray alloc] initWithArray:firstViewControl.listData];
[newArray addObject:@"42"];
[firstViewController setListData:[NSArray arrayWithArray:newArray]];
[newArray release];
不过,既然你要的对象添加到listArray
,它会更自然地用一个NSMutableArray
代替。此外,您目前正在向阵列中添加NSString
s,当它看起来更像是您想拥有NSNumber
对象时。
我应该在AppDelegate.h中有FirstViewController和SecondViewController的实例吗? – vburojevic
我不知道。我看不到你的AppDelegate.h文件,我不知道你的应用程序是如何组织的。上面的代码是我为你在SecondViewController.m中的' - (IBAction)insert'方法提出的。 – PengOne
我会尽力让你知道它是否有效:) 另一个问题,视图控制器之间共享变量的最佳方式是什么? – vburojevic
我不知道你是否有imported
SecondViewController.h,我想我有一个想法,你正在尝试做什么。
是的,这非常有帮助! :) 这是传递价值beetwen视图控制器的常用方式? – vburojevic
是的。它是:) .. – Legolas
另外,也许更容易,你可以在你的主AppDelegate中有变量。
把: int myNumber; 在projectname_AppDelegate.h文件
然后在每个视图控制器,您可以导入AppDelegate.h文件,然后像做:
的AppDelegate *的appDelegate =(AppDelegate中*)[[UIApplication的sharedApplication]代表]; 然后读取或修改:
appDelegate.myNumber
===
这是不是你应该做的事情所有的时间(你不想让你的appDelegate是一个巨大的数据存储库),但它可以让你在需要时快速修复...
我应该在其他视图控制器的每个方法中声明 AppDelegate * appDelegate =(AppDelegate *)[[UIApplication sharedApplication] delegate]; appDelegate.myNumb 如果我想在这些方法中使用该变量? 我很难搞清楚在视图控制器之间共享变量的最佳方法是什么... – vburojevic
在您的FirstViewController.h中,导入应用程序委托并具有变量AppDelegate * appDelegate;然后,在viewdidload中,说appDelegate =(AppDelegate *)[[UIApplication sharedApplication]委托]; ...然后,无论你需要它,只要参考appDelegate.myNumber –
更具可读性的代码: http://pastebin.com/GBk1V7ac – vburojevic
您可以在Stack Overflow上格式化代码,在单击'{}'时写入题。 – ryyst
@Wikiboo:让我知道如果该代码有帮助! – Legolas