开发者

Accessing variables from another ViewController

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
{
    /* He开发者_如何学Gore should be the code to insert some number in listData from FirstViewController */
}

So when the app loads it loads FirstViewController.xib and shows the listData array on screen, when I click button "Go to Insert" another view is loaded (SecondViewController.xib) with button "Insert" which should add some number into the array and display the new array on the first view.

How to do that?


You can access the parent view controller with self.parentViewController. Therefore something along these lines (meaning I haven't tested this -- you should) should work:

FirstViewController *firstViewController = self.parentViewController;
NSMutableArray *newArray = [[NSMutableArray alloc] initWithArray:firstViewControl.listData];
[newArray addObject:@"42"];
[firstViewController setListData:[NSArray arrayWithArray:newArray]];
[newArray release];

However, since you want to add objects to listArray, it would be more natural to use an NSMutableArray instead. Also, you are currently adding NSStrings to the array, when it looks more like you want to have NSNumber objects.


Alternately, and maybe easier, you could have the variables in your main AppDelegate.

Put: int myNumber; in the projectname_AppDelegate.h file

Then in each of your view controllers, you can import your AppDelegate.h file and then do something like:

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; and then read or change:

appDelegate.myNumber

===

This is not something you should be doing all the time (you don't want your appDelegate to be a giant data repository) but it could give you a quick fix when needed...


I do not know if you have imported the SecondViewController.h , and I think I have an idea an what you are trying to do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜