I want to display some data on table, let’s call it “TabeView” app.
So I created a “navigation-based” application on XCode and it gives me 4 files in the “classes folder”.
- RootViewController.h
- RootViewController.m
- TableViewAppDelegate.h
- TableViewAppDelegate.m
Now, I wanted to set up the data in TableViewAppDelegate using the “didFinishLaunchingWithOptions” method, which I did using an array.
Then, I need to “send” this array to the RootViewController. I have an array variable in RootViewController so I assume that I need to “set” the array variable in RootViewController from the TableViewAppDelegate. How can I do this?
The problem I am having is, that I don’t know how to set the array variable in RootViewController from TableViewAppDelegate. I want to know if something like below is possible
....
[RootViewController setMyArray:myArray];
[window addSubview:navigationController.view];
[window makeKeyAndVisible];
....
But I have no idea how to call “RootViewController”.
Hopefully I made some sense. Thank you.
First, create a property in your RootViewController class for the array variable. So e.g. if your array variable is called myArray your code might look something like this:
In RootViewController.h:
and add the corresponding @synthesize line in RootViewController.m:
Now you can set the myArray member of a RootViewController object like this:
Now, in your app delegate class, you can use the viewControllers property of self.navigationController to return the view controllers in the navigation stack. The root controller will always be at index 0. viewControllers will return an NSArray, whose elements are of type NSObject, so you need to cast to a RootViewController pointer too. Here it is in two lines, to make the cast explicit:
(In order to use the RootViewController class name in your app delegate class you’ll need to import the relevant header file – put this at the top of TableViewAppDelegate.m:
And that’s it!
p.s. Bear in mind that declaring your myArray property as type (nonatomic, retain) means that your RootViewController object will end up pointing to the same instance of NSArray that you pass to it. So, for example:
You can use (nonatomic, copy) instead, in which case your RootViewController object will make a copy of the array you pass in and retain that instead. Changes to the array once you’ve assigned it to your RootViewController object won’t affect the copy.