Manage Multiple ViewControllers from a TableView - iphone

I'm curious if anyone has ideas for managing multiple ViewControllers from a TableView. I have a list of roughly seven items I am displaying in a TableView with a ViewController dedicated to each. My first thought is to initialize an array with the various ViewControllers.
NSMutableArray *viewControllers = [[NSMutableArray alloc] initWithCapacity:7];
[viewControllers addObject:[[ViewController1 alloc] initWithNibName:#"View1" bundle:nil]];
[viewControllers addObject:[[ViewController2 alloc] initWithNibName:#"View2" bundle:nil]];
...
Then reference that array to load the appropriate view on item selection.
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[self.navigationController pushViewController:[viewControllers objectAtIndex:indexPath.row] animated:YES];
}
I'm really not sure if this is an appropriate approach. Any direction would be great.
EDITED:
Based on the feedback from Ryan and Joe I implemented an object to hold my table items. Abbreviating my problem also caused some confusion on implementation details. Added the full solution to manage both view controllers and selecting tab bar items.
TableNavigationItem.h
#import
#interface TableNavigationItem : NSObject {
NSString *title;
NSNumber *tabIndex;
id viewController;
}
#property (nonatomic, retain) NSString *title;
#property (nonatomic, retain) NSNumber *tabIndex;
#property (nonatomic, retain) id viewController;
#end
TableNavigationItem.m
#import "TableNavigationItem.h"
#implementation TableNavigationItem
#synthesize title;
#synthesize viewController;
- (id) init{
if(self = [super init]){
self.title = #"";
}
return self;
}
- (void) dealloc {
[title release];
[tabIndex release];
[viewController release];
[super dealloc];
}
#end
Then initialize per Joe's suggestion.
NSMutableArray *mutableArray = [[NSMutableArray alloc] initWithCapacity:7];
TableNavigationItem *navItem;
// view 1
navItem = [[TableNavigationItem alloc] init];
navItem.title = #"View 1";
navItem.tabIndex = [NSNumber numberWithInt:1];
[mutableArray addObject:navItem];
[navItem release];
// view 2
navItem = [[TableNavigationItem alloc] init];
navItem.title = #"View 2";
navItem.viewController = [ViewController2 class]];
[mutableArray addObject:navItem];
[navItem release];
...
// store the navigation items
self.tableItems = [NSArray arrayWithArray:mutableArray];
[mutableArray release];
Then
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
TableNavigationItem *navItem = [tableItems objectAtIndex:indexPath.row];
if(navItem.viewController != nil){
[self.navigationController pushViewController:[[[navItem.viewController alloc] init] autorelease] animated:YES];
}
else if(navItem.tabIndex != nil){
[((MyAppDelegate *)[UIApplication sharedApplication].delegate).tabBarController setSelectedIndex:[navItem.tabIndex integerValue]];
}
}

If all the views those controllers manage are visible on the screen immediately, there is nothing wrong with that approach. Make sure you release the array of VC's in -viewDidUnload, and recreate it in -viewDidLoad, so the runtime can unload all those extra objects when the next view is pushed onscreen. And be aware, only the root view controller will receive view lifecycle events; The view controllers you create and manually add the owned views to the table will not get those methods called. You'll have to implement some plumbing to get those view lifecycle events into the 'subviews', through notification or delegation.
The best answer to your question is "Instrument it". Run the Allocations and VM instruments at a minimum, and check to see how much memory those view controllers are consuming. If you want to improve your skillz with Instruments, watch the Performance session from WWDC 2011, they did a great job teaching how to use it to find memory and performance issues.

That sounds fine to me. The only concern I would have is whether your view controllers are RAM-heavy, in which case you may want to make a decision: is it better to preallocate everything (i.e. are you sure you can fit all of those controllers' state within available memory?) or is it better to take the latency hit to load the appropriate view controller as-needed?
It looks like your ViewControllers are of different classes. If that's the case (and if each one always uses the same respective nib), I would consider implementing a custom -init method on each and making your array of choices one of Class objects. That's just a matter of personal preference, though.
One more thing: You will want to autorelease those view controllers or you'll leak memory no matter what.

Related

How many ways to pass/share data b/w view controller

im new to IOS and Objective-C and the whole MVC paradigm and i'm stuck with the following.
I am working on (replica) Contact app, also available in iphone as build in app. i want to pass data through another view controller and the data is pass (null) :(.
My Question is, How do I transfer the data from one view to another?
As most the answers you got, passing data between one controller and another just means to assign a variable from one controller to the other one.
If you have one controller to list your contacts and another one to show a contact details and the flow is starting from the list and going to detail after selecting a contact, you may assign the contact variable (may be an object from the array that is displayed in your list) and assign it to the detail view controller just before showing this one.
- (void)goToDetailViewControllerForContact:(Contact *)c
{
ContactDetailViewController *detailVC = [[[ContactDetailViewController alloc] init] autorelease];
detailVC.contact = c;
[self.navigationController pushViewController:c animated:YES];
//[self presentModalViewController:detailVC animated:YES]; //in case you don't have a navigation controller
}
On the other hand, if you want to insert a new contact from the detail controller to the list controller, I guess the best approach would be to assign the list controller as a delegate to the detail one, so when a contact is added the delegate is notified and act as expected (insert the contact to the array and reload the table view?).
#protocol ContactDelegate <NSObject>
- (void)contactWasCreated:(Contact *)c;
// - (void)contactWasDeleted:(Contact *)c; //may be useful too...
#end
#interface ContactListViewController : UIViewController <ContactDelegate>
#property (nonatomic, retain) NSArray *contacts;
...
#end
#implementation ContactListViewController
#synthesize contacts;
...
- (void)goToDetailViewControllerForContact:(Contact *)c
{
ContactDetailViewController *detailVC = [[[ContactDetailViewController alloc] init] autorelease];
detailVC.contact = c;
detailVC.delegate = self;
[self.navigationController pushViewController:c animated:YES];
//[self presentModalViewController:detailVC animated:YES]; //in case you don't have a navigation controller
}
- (void)contactWasCreated:(Contact *)c
{
self.contacts = [self.contacts arrayByAddingObject:c]; //I'm not sure this is the correct method signature...
[self reloadContacts]; //may be [self.tableView reloadData];
}
...
#end
#interface ContactDetailViewController : UIViewController
#property (nonatomic, assign) id<ContactDelegate> delegate;
...
#end
#implementation ContactDetailViewController
#synthesize delegate; //remember to don't release it on dealloc as it is an assigned property
...
- (void)createContactAction
{
Contact *c = [[[Contact alloc] init] autorelease];
[c configure];
[self.delegate contactWasCreated:c];
}
...
#end
Technically, you shouldn't!
The whole idea is not for "views" to control what happens to the data.
What you want to do is to pass data between controllers (which I imagine is exactly what you are planning to do anyway).
You can have shared model (an instance of an object that both view controllers would access) keeping the data you want to share,
You can use notifications to pass data (it is best suited for certain cases).
You can write something to disk and read it again later.
You can use NSUserDefaults.
You can use KeyChain.
...
The best way is:
declare the appropriate #property in the second view controller
when you create it, simply set the property with
viewController.property = valueYouWantToPass;
I'm a big fan of delegates and protocols.
And in some occasions use a Singleton pattern.
two ways to pass/share data between view controller
create an object and sent the data like this
QGraduteYr *tableverify=[[QGraduteYr alloc]initWithStyle:UITableViewStyleGrouped];
tableverify.mystring=myString
[self.navigationController pushViewController:tableverify animated:YES];
another method is stor it in the delegates and use it via shared delegates
MedicalAppDelegate *appdelegate=(MedicalAppDelegate *)[[UIApplication sharedApplication]delegate];
appdelegate.collnameStr=collStr;
and ust this appdelegates value whereever you need

UITableViewController does not refresh

I have a tabBar application. In the app delegate i create one NSMutableArray, one UITableViewController and one class (lets say class B) that updates the NSMutableArray.
The tabBar contains
a) The tableViewController which shows the data in the *booksArray
b) Class B which adds data to the booksArray
The tableView works great when it is first loaded. The problem is that when the array updates, not any changes are fired in the UItableViewContoller (when I choose its tab again). Do I have to use delegation? Do I have to change my architecture?
AppDelegate:
visibleBooks = [[NSMutableArray alloc] init];
UINavigationController *navController = [[UINavigationController alloc]
initWithRootViewController:booksTableViewController];
UITabBarController *tabBarController = [[UITabBarController alloc] init];
NSArray *viewControllers = [NSArray arrayWithObjects:navController,qrViewController, nil];
[tabBarController setViewControllers:viewControllers];
In the UITableViewController .h:
#class BookDetailedViewController;
#interface BooksTableViewController : UITableViewController {
NSMutableArray *bookSource;
}
#property (nonatomic,retain) NSMutableArray *bookSource; // IS RETAIN OK?
- (id) initWithDataSource: (NSMutableArray *) source;
#end
In the UITableViewController .m:
- (id) initWithDataSource: (NSMutableArray *) source
{
[super initWithStyle:UITableViewStyleGrouped];
[self setBookSource:source];
[[self navigationItem] setTitle:#"Books"];
return self;
}
You need to invoke [self.tableView reloadData] in UITableViewController each time when your data source is updated, or when you're showing your tableView.
This can be done in viewWillAppear: inside your BooksTableViewController, or in tabBar:didSelectItem: inside UITabBarController.
for example, add this code snippet to BooksTableViewController:
- (void) viewWillAppear:(BOOL) animated
{
[super viewWillAppear:animated];
[self.tableView reloadData];
}

dimissModalViewControllerAnimated causing tableView to be full screen?

I have a RootViewController with 2 tableViews as subviews (created in IB) each with their own tableViewController class (handleing fetchRequests etc.)
1 tableView is static (no data changed by user or modelViews).
tableView 2 has a button in the header which presents an imagePickerController.
No issues so far.
Problem is, when i dismiss the imagePicker
[self dismissModalViewControllerAnimated:YES];
TableView 2 becomes full screen i have tried
[[self rootViewController] dismissModalViewControllerAnimated:YES]
Nothing happens at all. It sticks on the image picker.
I suspect this is due to there being very little of the view being created programmaticaly.
Any ideas?
Thanks in advance.
DetartrateD
-(IBAction)addImageTableAPressed {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
[self presentModalViewController:imagePicker animated:YES];
[imagePicker release];
}
RootViewController
|| ||
|| ||
\/ \/ addImageTableAPressed
TableViewControlA TableViewControlB --------------------->modelViewController
To resolve mananagedObjectContect.....
- (void)viewDidLoad {...
if(managedObjectContext == nil)
{
managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSLog(#"After managedObjectContext: %#", managedObjectContext);
}
...
}
As I mentioned in one of my comments, I would prefer having a single view controller managing the two table views. Define a UIView (the rootView) including 2 subviews (tableViewA and tableViewB). Your RootViewController's view will be rootView, and this controller will have to be the data source and delegate of both table views. The code I will give here is by no means complete nor optimal, but gives you a good idea of what is needed to implement my solution.
For example:
#interface RootViewController <UITableViewDelegate, UITableViewDataSource> {
NSArray *dataArrayA;
NSArray *dataArrayB;
UITableView tableViewA;
UITableView tableViewB;
NSManagedObjectContext *context;
}
#property (nonatomic, retain) NSArray *dataArrayA;
#property (nonatomic, retain) NSArray *dataArrayB;
// in IB, link the dataSource and delegate outlets of both tables to RootViewController
#property (nonatomic, retain) IBOutlet UITableView tableViewA;
#property (nonatomic, retain) IBOutlet UITableView tableViewB;
// this property will allow you to pass the MOC to the RootViewController from
// the parent view controller, instead of accessing the app delegate from RootViewController
#property (nonatomic, retain) NSManagedObjectContext *context;
// ... etc.
#end
#implementation RootViewController
#synthesize dataArrayA;
#synthesize dataArrayB;
#synthesize tableViewA;
#synthesize tableViewB;
#synthesize context;
// initialize dataArrayA and dataArrayB
- (void)viewDidLoad {
[super viewDidLoad];
NSError *error = nil;
// initialize and configure your fetch request for data going into tableViewA
NSFetchRequest fetchRequestA = [[NSFetchRequest alloc] init];
// configure the entity, sort descriptors, predicate, etc.
// ...
// perform the fetch
self.dataArrayA = [context executeFetchRequest:fetchRequestA error:&error];
// do the same for the data going into tableViewB - the code is very similar, you
// could factor it out in a private method instead of duplicating it here
// NSFetchRequest fetchRequestB = [[NSFetchRequest alloc] init];
// omitting the details ... etc.
self.dataArrayB = [context executeFetchRequest:fetchRequestB error:&error];
// release objects you don't need anymore, according to memory management rules
[fetchRequestA release];
[fetchRequestB release];
}
// Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// if you have a different number of sections in tableViewA and tableViewB
/*
if (tableView == tableViewA) {
return ??;
} else {
return ??
}
*/
// otherwise, if both table views contain one section
return 1;
}
// Customize the number of rows in each table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == tableViewA) {
return [dataArrayA count];
} else {
return [dataArrayB count];
}
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = nil;
if (tableView == tableViewA) {
// get the data for the current row in tableViewA
id objectA = [dataArrayA objectAtIndex:indexPath.row];
// configure the cell for tableViewA
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierA];
// etc...
} else {
// get the data for the current row in tableViewB
id objectB = [dataArrayB objectAtIndex:indexPath.row];
// configure the cell for tableViewB
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierB];
// etc...
}
return cell;
}
// And so on, the same idea applies for the other UITableViewDelegate you would need to
// implement...
- (void)dealloc {
[dataArrayA release];
[dataArrayB release];
[tableViewA release];
[tableViewB release];
[context release];
// etc...
[super dealloc];
}
#end
I hope you'll find this useful.

Pushing UITableViewController onto [self navigationController] causes an EXC_BAD_ACCESS

In the current view that I am in, a button touch-up-inside event leads to the following action:
(Note that while in the Debugger, I've verified that both [self navigationController] and the instantiated historyViewController do indeed exist.
I am unable to determine why this bad access is happening. I can pop/push this view/other views from the navigation controller. Any ideas on how to go about investigating why this view in particular is having problems when getting pushed onto the nav controller?
-(IBAction) viewOrEditHistory: (id) sender {
HistoryViewController *historyViewController = [[HistoryViewController alloc] initWithStyle:UITableViewStyleGrouped];
historyViewController.title = #"View or Edit by date";
historyViewController.sameExSessions = [[NSMutableArray alloc] init];
historyViewController.exercise = [[Exercise alloc] initWithName:self.title muscleGroup:muscleGroupLabel.text];
/*** EXC_BAD_ACCESS happens after following line is executed ***/
[[self navigationController] pushViewController:historyViewController animated:YES];
}
Here is my HistoryViewController.h
#import
#interface HistoryViewController : UITableViewController {
NSMutableArray *sameExSessions;
Exercise *exercise;
}
#property (nonatomic, retain) NSMutableArray *sameExSessions;
#property (nonatomic, retain) Exercise *exercise;
-(NSMutableArray *) SameExerciseSessionList;
-(NSString *) getDocPath;
-(NSInteger) tableView:(UITableView *) tableView numberOfRowsInSection: (NSInteger)section;
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath;
#end
Please also get your memory management straight or you will run into a lot more problems. Every alloc should be followed by either a release or an autorelease.

How to assign managedObjectContext to a dynamic viewController?

I have 4 buttons on main screen, each one sends me to a viewController. The third one, sends me to a view on which I wanna set the managedObjectContext. If I use the class name to create an instance, it's all right. But I'm looking for a way to use just one method that uses an array to retrieve the name of the Class for the needed viewController. But it's leading to an error message, like it doesn't exist on the destination viewController??? Anyone have any ideas about this aproach??? Thanks in advance!
Here is the code:
NSArray *viewControllers = [[NSArray alloc]
initWithObjects:#"nil",#"OpcoesView",#"nil",#"TheNames", nil];
NSString *viewName = [viewControllers objectAtIndex:[sender tag]]; //the taped button tag
UIViewController *viewController = [[NSClassFromString(viewName) alloc]
initWithNibName:viewName bundle:nil];
if ([sender tag] == 3) {
viewController.managedObjectContext = contexto;
}
You do not need to know the subclass at all. Because Objective-C is a dynamic language and messages are resolved at runtime, you can send the message without having to know anything about the subclass at all.
First I would refer to the subclass as an id (instead of UIViewController) and as long as you have its header imported you can call [viewController setManagedObjectContext:contexto] directly.
However if you don't want to or can't import the header then just use KVC as follows:
[viewController setValue:contexto forKey:#"managedObjectContext"];
I would keep MOC in my app delegate instead of assigning it down to every of my viewControllers:
And in my viewController .m file:
#import "MyAppDelegate.h" // Assuming you have a property called managedObjectContext in your MyAppDelegate
#interface MyViewController (PrivateMethgods)
#property (nonatomic, readonly) NSManagedObjectContext * managedObjectContext;
#end
#implementation MyViewController
#dynamic managedObjectContext
- (NSManagedObjectContext *)managedObjectContext {
MyAppDelegate *appDelegate = (MyAppDelegate *)[UIApplication sharedApplication].delegate;
return appDelegate.managedObjectContext;
}
So I can use it in my viewController like this:
if ([self.managedObjectContext hasChanges]) {
...
}
To set a property that is only in the subclass view controller (such as "managedObjectContext"), you can take advantage of the fact that you know the type like this:
NSArray *viewControllerNames = [[NSArray alloc] initWithObjects:#"nil",#"OpcoesView",#"nil",#"TheNames", nil];
NSString *viewControllerName = [viewControllerNames objectAtIndex:[sender tag]]; //the tapped button tag
UIViewController *viewController = [[NSClassFromString(viewControllerName) alloc] initWithNibName:viewControllerName bundle:nil];
if ([sender tag] == 3) {
TheNames *namesVC = (TheNames*)viewController;
namesVC.managedObjectContext = contexto;
}