Objective-C (iOS): prepareForSegue won't pass my data into destination VC - objective-c

VC1 = NewGameViewController
VC2 = GameViewController
NewGameViewController.m
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if( [segue.identifier isEqualToString:#"newGameSegue"]) {
GameViewController *gameVC = (GameViewController *)segue.destinationViewController;
NSArray *array = [self nameArrayForTextFieldArray:self.namePicker.textFieldArray withColon:YES];
gameVC.nameArray = [[NSArray alloc] initWithArray:array];
}
-(NSArray *)nameArrayForTextFieldArray:(NSArray *)array withColon:(BOOL *)bool
basically returns an nsarray of strings given an nsarray of textfields. withcolon is a bool of whether or not you want the strings to have a colon appended to the end.
when i debug my code, the _nameArray ivar in gameVC still reads nil after every line here is called...can anyone help me out here??

The prepareForSegue method is invoked by UIKit when a segue from one screen to another is about to be performed. It allows us to give data to the new view controller before it will be displayed. Usually you’ll do that by setting its properties.
The new view controller can be found in segue.destinationViewController. If GameViewController embed the navigation controller, the new view controller will not be GameViewController but the navigation controller that embeds it.
To get the GameViewController object, we can look at the navigation controller’s topViewController property. This property refers to the screen that is currently active inside the navigation controller.
To send an object to the new view controller you can use this solution using performSegueWithIdentifier:
For example, if we want to perform a segue pressing a UIButton we can do this:
In the MyViewController.h we create a IBAction (connected to UIButton), dragging the button from storyboard to code:
- (IBAction)sendData:(id)sender;
In MyViewController.m we implement the method:
- (IBAction)sendData:(id)sender
{
NSArray *array = [self nameArrayForTextFieldArray:self.namePicker.textFieldArray withColon:YES];
[self performSegueWithIdentifier:#"newGameSegue" sender:array];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"newGameSegue"]) {
UINavigationController *navigationController = segue.destinationViewController;
GameViewController *controller = (GameViewController *)navigationController.topViewController;
controller.nameArray = sender;
}
}

Is GameViewController embedded in a navigation controller? In that case, your destinationViewController property is of type UINavigationController, not GameViewController. You can get to GameViewController by calling [segue.destinationViewController.viewControllers lastObject].

I'm assuming that you've done a NSLog (or examine it in the debugger) of array immediately before setting gameVC.nameArray. You really want to make sure it's being set the way you think it is. It's amazing how many times I've spent debugging something like this only to realize the problem was in my equivalent to nameArrayForTextFieldArray. Or a typo in the name of the segue identifier. Or random things like that.
Assuming that's ok, then a couple of things are possible:
How is your nameArray property defined in GameViewController? If it's not a strong reference (or a copy), then when your array falls out of scope, it will be deallocated. I think this would manifest itself slightly differently, but it's worth confirming.
Also, I've seen situations where a controller like GameViewController might have some confusion between various ivars and properties (which is why I never define ivars for my properties ... I let #synthesize do that).
I assume you're not using a custom setter for nameArray. I just want to make sure. If so, though, please share that, too.
Bottom line, can you show us all references to nameArray in your #interface of GameViewController as well as in its #synthesize statement?

Related

Use IBOutlets on different ViewController storyboard

I have a storyboard app with two different ViewController. On the second ViewController I have a UIImageView and I would like to call that UIImageView on the first one. I've been looking for a solution but I can't find anything that work for me.
#property(nonatomic, retain) IBOutlet UIImageView *pic;
I just want to be able to use that UIImageView on the other viewcontroller. I hope you can help me.
EDIT:
yes you can try to set your UIImageView in prepare for segue. I have tried it and it seems to work. You would do it as follows:
**I am assuming that the controller you are seguing to is called NewViewController
**I am also assuming your NewViewController has a UIImageView called imageView
-(void)prepareForSegue....
{
if ([segueIdentifier isEqual....])
{
NewViewController *newController=(NewViewController *)[segue destinationViewController];
[[newViewController imageView]setImage:self.someUIImageFromCurrentClass];
[[newViewController imageView]setNeedDisplay];
}
}
and yes, you do have to create a UIImage in current class (in this case it's self.someUIImageFromCurrentClass). That's the point is that you're taking an image from current ViewController (current class) and showing it in the ViewController you are seguing to.
ORIGINAL:
-(void) prepareForSegue: (UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"your segue name"])
{
[segue.destinationViewController setYourUIImage:self.someImageFromCurrentClass];
}
}
be sure to import the .h file for the controller you're seguing to.
second, YourUIImage is an UIImage that is publicly declared in the controller you're seguing to (like Michael mentioned).
In the destination controller, you'll want to grab that UIImage and set it as the image for you UIImageView:
[self.myImageView setImage:YourUIImage]; // <-- you can do this in ViewDidLoad or ViewWillAppear
that should get you going
**Also I guess it's worth mentioning is that a segue always creates a new instance of the controller you're seguing to, which doesn't exist before the segue, which is why you have to pass the image to it.
You can't use outlets between view controllers (VCs) because there's no automatic one for one VC to refer to another. You'll have to expose public properties or methods that allow the manipulation you need and find some way to pass a reference to one VC from another.
For example, if you pass from one VC to another via a segue, you can manipulate properties in the destination VC from the source in prepareForSegueWithIdentifier:.

Passing Objects using Segue

I have trouble understanding segues and how they work and pass objects. Basically I have a calculator and am trying to graph the objects stored in an array. So far I have an object called brain which is an instance of CalculatorBrain. Now brain has an NSArray property that I use as a stack to store variables. Let's say I add the values 3 and 5 to the array and then want to segue. I have my segue selected to a button called "Graph" so when I click the button it segues. How would I pass brain to the new view controller that I am segueing to? I have a property called setGraphingPoint which is defined in the new view controller which I think should accept the passed object. Also, if I pass brain through a segue will the values 3 and 5 be passed along with it or will it create a new object of CalculatorBrain? Here is what I have so far.
This is defined in the new view controller
#property (nonatomic, strong) CalculatorBrain *graphingPoint;
#synthesize graphingPoint = _graphingPoint;
-(void) setGraphingPoint:(CalculatorBrain*) graphingPoint{
_graphingPoint = graphingPoint;
[self.graphingView setNeedsDisplay];
}
This is called from the old view controller which will have button to segue
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([segue.identifier isEqualToString:#"Graph"])
[segue.destinationViewController setGraphingPoint:[self.brain program]];
You can use protocols. For instance, you can have your prepareForSegue look like this:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
id destination = segue.destinationViewController;
if([destination conformsToProtocol:#protocol(GraphPointUsing)])
[destination setGraphingPoint:[self.brain program]];
}
Then you just have to make sure the the ViewController that you are segueing to conformist to GraphPointUsing.
If you do not want to use protocols, but you still want to call methods on GraphPoint you can do this:
//In new ViewController suppose we want to call the method `foo` on `GraphPoint`
[self.graphingPoint foo];
//Or if we want to call a setter we can do
[self.graphingPoint setFoo:5];

Simple Passing of variables between classes in Xcode

I am trying to do an ios app but I am stuck at passing data between classes .
This is my second app . The first one was done whit a global class , but now I need
multiple classes . I tried many tutorials , but did not work or the passed value was always zero . Can someone please write me a simple app to demonstrate passing of variables in IOS 5 .
Nothing special , storyboard whith 2 view controllers , one variable .
Thank you for your help .
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
FirstViewController *fv;
fv.value = indexPath.row;
NSLog(#"The current %d", fv.value);
FirstViewController *detail =[self.storyboard instantiateViewControllerWithIdentifier:#"Detail"];
[self.navigationController pushViewController:detail animated:YES];
}
here is the code from my main view and i need to send the indexPath.row or the index of the cell that i pressed to the next view
There are several things to do. Depending on the app, you could either add a variable to the AppDelegate class, making it availible to all classes through a shared instance. The most common thing (I think) is to make a singleton. For that to work, you can make a class, say StoreVars, and a static method that returns the object, which makes the class "global". Within the method, you initialize all your variables, like you always would. Then you can always reach them from wherever.
#interface StoreVars : NSObject
#property (nonatomic) NSArray * mySharedArray;
+ (StoreVars*) sharedInstance;
#implementation StoreVars
#synthesize mySharedArray;
+ (StoreVars*) sharedInstance {
static StoreVars *myInstance = nil;
if (myInstance == nil) {
myInstance = [[[self class] alloc] init];
myInstance.mySharedArray = [NSArray arrayWithObject:#"Test"];
}
return myInstance;
}
This will make a singleton. If you remember to import "StoreVars.h" in your two viewControllers, you can access the now shared array like this;
[StoreVars sharedInstance].mySharedArray;
^
This is a method returning a StoreVars object. Within the StoreVars class, you can implement any object and initialize it in the static method. Just always remember to initialize it, or else, all your object will be 0/nil.
If you are not a fan of the UINavigationController and would rather use segues, it's a lot easier, but can make your app rather "messy" imo. There is a method implemented in UIViewController you should overload:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Make sure your segue name in storyboard is the same as this line
if ([[segue identifier] isEqualToString:#"YOUR_SEGUE_NAME_HERE"])
{
// Get reference to the destination view controller
YourViewController *vc = [segue destinationViewController];
// Pass any objects to the view controller here, like...
[vc setMyObjectHere:object];
}
}
source: How to pass prepareForSegue: an object
Do some research before asking questions like this. Read some tutorials, and try out yourself, and then ask questions related to what you are really looking for. It's not everyday people want to do all the work for you, but sometimes you're lucky. Like today.
Cheers.
if you use segue between 2 controllers you must overload prepareToSegue method
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// check if it's the good segue with the identifier
if([[segue identifier] isEqualToString:#"blablabla"])
{
// permit you to get the destination segue
[segue destinationViewController];
// then you can set what you want in your destination controller
}
}
The problem you face is quite perplexing for beginners. "Solving" it wrong way can result in learning a ton of bad habits.
Please have a look at Ole Begemann's excellent tutorial on Passing Data Between View Controllers - it's really worth reading.

Xcode 4.2 & Storyboard, how to access data from another class?

I was wondering how I could access data from another class using Xcode 4.2 and Storyboard?
Say for instance how would I access the text of a text field from another class?
Google hasn't helped and the lesson on MyCodeTeacher.com about this is outdated and doesn't work anymore...
Thanks for bearing with me!
-Shredder2794
Not sure if this is the only or best way, but you can create a property in the destination view's .h file and set it to a value before the segue is performed
in the destination view controller's .h file:
#interface YourDestinationViewController : UIViewController
{
NSString* _stringToDisplay;
//...
}
#property (nonatomic, retain) NSString* stringToDisplay;
//...
and in the presenting view's .m file
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
YourDestinationViewController*viewController = segue.destinationViewController;
viewController.delegate = self;
viewController.stringToDisplay = #"this is the string";
}
Then you can do what you want with the property in whichever of the viewWillAppear/viewDidLoad/viewDidAppear/etc. methods best suits your purpose in the destination view's .m file
And then to check if it works, in the destination view controller's .m file:
-(void)viewWillAppear:(BOOL)animated
{
NSLog(#"self.stringToDisplay = %#", self.stringToDisplay);
...
//and if a label was defined as a property already you could set the
//label.text value here
}
Edit: Added more code, and made it less generic
This isn't specific to Storyboard. There are several ways to do what you are trying to do. You could declare a variable in your AppDelegate (an NSString) and set that in your first class. Then in your second class access the AppDelegate variable and use that to set your label. The code to do this is:
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
label.text = appDelegate.myString;
Another way to do it (probably the easiest) is to declare an NSString in your second class. Then in your first class, before you push the second view set that string variable. Something like this:
MyViewController *vc = [[MyViewController alloc] initWithNibName:#"" bundle:nil];
vc.myString = #"";
The third way to do this is using delegates. This is the most 'complicated' way but is the best. You would create a delegate which gets called when your second view appears. The delegate could then return the value from the first class to you.
You may also be able to use the new completion handler block on the iOS 5 pushViewController: method.
Edit:
Custom init method:
- (void)initWithNibName:(NSString *)nibName bundle:(NSString *)bundle string:(NSString *)myString
And then when you are pushing the view just class this method and set the string through it.

UIViewController parentViewController access properties

I know this question has been asked several times and I did read existing posts on this topic but I still need help.
I have 2 UIViewControllers - parent and child. I display the child UIViewController using the presentModalViewController as below:
ChildController *child =
[[ChildController alloc] initWithNibName:#"ChildView" bundle:nil];
[self presentModalViewController:child animated:YES];
[child release];
The child view has a UIPickerView. When user selects an item from UIPickerView and clicks done, I have to dismiss the modal view and display the selected item on a UITextField in the parent view.
In child's button click delegate, I do the following:
ParentController *parent =
(ParentController *)[self.navigationController parentViewController];
[parent.myTextField setText:selectedText];
[self dismissModalViewControllerAnimated:YES];
Everything works without errors. But I don't know how to load the parent view so that it displays the updated UITextField.
I tried
[parent reloadInputViews];
doesn' work. Please help.
Delegation is the way to go. I know some people that may be looking for an easier solution but trust me I have tried others and nothing works better than delegation. So anyone having the same problem, go read up on delegation and follow it step by step.
In your subviewcontroller.h - declare a protocol and declare delegate mthods in it.
#protocol myDelegate
-(void)clickedButton:(subviewcontroller *)subController;
#end
In your subviewcontroller.h, within #interface:
id<myDelegate> delegate;
#property (nonatomic, assign) id<myDelegate> delegate;
NSString *data;
-(NSString *)getData;
In your subviewcontroller.m, synthesize myDelegate. Add the following code to where you want to notify your parentviewcontroller that the subview is done doing whatever it is supposed to do:
[delegate clickedButton:self];
and then handle getData to return whatever data you want to send to your parentviewcontroller
In your parentviewcontroller.h, import subviewcontroller.h and use it's delegate
#import "subviewcontroller.h"
#interface parentviewcontroller : VUIViewController <myDelegate>
{}
In your parentviewcontroller.m, implement the delegate method
- (void)clickedButton:(subviewcontroller *)subcontroller
{
NSString *myData = [subcontroller getData];
[self dimissModalViewControllerAnimated:YES];
[self reloadInputViews];
}
Don't forget memory management!
If a low-memory warning comes in during your modal view's display, the parent's view will be unloaded. Then parent.myTextField is no longer referring to the right text field until the view is reloaded. You can force a reload of the view just by calling parent.view;
However, a better idea might be to have the parent view have a String property that can be set by the child view. Then, when the parent view reappears, put that data into the text field, inside viewWillAppear: for example. You'd want to have the value set to some default value for when the parent view initially shows up too.
-(void) viewWillAppear:(BOOL) animated doesn't get called for me either, exactly when it's a modal view controller. No idea why. Not incorrectly overridden anywhere in this app, and the same problem occurs on the other 2 apps I'm working on. I really don't think it works.
I've used the delegate approach before, but I think that following approach is pretty good as well.
I work around this by adding a private category to UIViewController, like so:
.h file:
#interface UIViewController(Extras)
// returns true if this view was presented via presentModalViewController:animated:, false otherwise.
#property(readonly) BOOL isModal;
// Just like the regular dismissModalViewController, but actually calls viewWillAppear: on the parent, which hasn't been working for me, ever, for modal dialogs.
- (void)dismissModal: (BOOL) animated;
#end
and .m file:
#implementation UIView(Extras)
-(BOOL) isModal
{
return self == self.parentViewController.modalViewController;
}
- (void)dismissModal: (BOOL) animated
{
[self.parentViewController viewWillAppear: animated];
[self dismissModalViewControllerAnimated: animated];
}
#end
which I can now call like this when I want to dismiss the dialog box:
// If presented as a modal view, dismiss yourself.
if(self.isModal)
[self dismissModal: YES];
and now viewWillAppear is correctly called.
And yes, I'm donating a bonus 'isModal' property, so that the modal view can tell how it was being presented, and dismiss itself appropriately.