calling functions and passing information between views - iphone

Thanks in advance for your help!
In the main ViewController.m of my project I am adding a customized tableView like so:
messageController = [[MyMessagesController alloc] initWithStyle:UITableViewStylePlain];
[self addChildViewController:messageController];
[self.view addSubview:messageController.view];
Then, in the MyMessagesController.m section tableView didSelectRowAtIndexPath: I'd like to write code that would take effect in the ViewController.m where it was created and added as a childViewController.
How can I access the functions of the ViewController.m from MyMessagesController.m?
Can I make it a delegate somehow so I could call [delegate functionName];?
Could I pass information back to the ViewController.m? About which of the rows in table was selected by sending through an NSString or NSArray or anything?

Yes, use a delegate, if you are unsure how best to accomplish this, here is a good reference from Apple about delegate programming

Got it figured out, here's how you turn one viewController into a delegate for another:
In the .h of the parent controller -
#interface ViewController : UIViewController <NameOfDelegate> {
In the .m of the parent controller, once you create the new view -
newViewController.delegate = self;
and also:
- (void)functionToCall:(id)sender {
NSLog(#"Function Called!!!");
}
In the .h of the newViewController you're adding -
#protocol NameOfDelegate;
#interface newViewController : UIViewController/OR/TableViewController {
id <NameOfDelegate> delegate;
}
#property (nonatomic, strong) id <NameOfDelegate> delegate;
#end
#protocol NameOfDelegate
- (void)functionToCall:(id)sender;
#end
in the .m of the newViewController -
#implementation newViewController
#synthesize delegate;
and when you're ready to call the function in your delegate -
[delegate functionToCall:self];

Related

IOS setting a custom delegate

I'm working through the IOS HelloWorld example and I have a question regarding setting the delegate for a TextField. In the example it was as easy as control-dragging from the TextField to the ViewController. But now say I wanted to create a custom class to act as my delegate as so:
#import <Foundation/Foundation.h>
#interface SweetAssDelegate : NSObject <UITextFieldDelegate>
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField;
#end
#import "SweetAssDelegate.h"
#implementation SweetAssDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField
{
NSLog(#"Calling Delegate");
[theTextField resignFirstResponder];
return YES;
}
#end
How can I set this class to be the delegate of the TextField? As far as I can tell there is not way to accomplish this through the GUI. I tried manually setting the delegation after window load with no success:
#import "ViewController.h"
#import "SweetAssDelegate.h"
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UITextField *inputField;
#end
- (void)viewDidLoad
{
[super viewDidLoad];
SweetAssDelegate *foo = [[SweetAssDelegate alloc] init];
[self.inputField setDelegate:foo];
NSLog(#"Delegate: %#", self.inputField.delegate);
}
I actually receive some sort of memory exception when bringing up the keyboard? Any ideas? Thanks.
As a side question, where should I always use viewDidLoad to initialize any variables? I noticed that init was not being called???
Your delegate object, foo, is allowed to fall out of scope and is released at the end of viewDidLoad and by the time the keyboard comes up, it doesn't exist anymore. Make it an ivar (or property) of your view controller, or otherwise make sure that foo doesn't fall out of scope at the end of viewDidLoad.
Thus, it could be something like:
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UITextField *inputField;
#property (strong, nonatomic) SweetAssDelegate *foo;
#end
- (void)viewDidLoad
{
[super viewDidLoad];
self.foo = [[SweetAssDelegate alloc] init];
[self.inputField setDelegate:self.foo];
NSLog(#"Delegate: %#", self.inputField.delegate);
}
Your textfield delegate must have the implemented to be your textfield delegate I guess.
A delegate manages the communication between objects, which means your custom delegate must allow communication between objects and must provide methods, the textfield can work with...
Another example is a tableView:
You can make a custom delegate which implements the delegates and then calls some tableview related Methods...
Here this code might be interesting for you:
#interface myCustomDelegateForTextFields <UITextFieldDelegate>
#end
#implementation myCustomDelegateForTextFields
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
return TRUE;
}
#end
#implementation ViewController
myCustomDelegateForTextFields *txtfielddelegate = [[myCustomDelegateForTextFields alloc] init];
UITextField *whatever;
whatever.delegate = txtfielddelegate;
//your textfield now listens to the BOOL method in your custom delegate
#end
Is it that what u were looking for? :)
you can ofc pack the myCustomDelegateForTextField delegate in another class and call the class

EXD_BAD_ACCESS passing data back to delegate

I'm a relatively new iPhone developer and am making great progress building my 2nd iPhone app. In the app I'm building now I'm doing some code separation with some protocols and delegates so that I car re-use some of my code in a variety of places throughout my code.
Here's what I want to happen:
CITRootViewController creates an instance of a CITReportCreator class, passing itself as a property so that the reportCreator can open additional view controllers and such.
CITReportCreator class is declared as implementing the CITImageCaptureDelegate protocol, which is declared in the CITImageCaptureViewController file.
CITImageCaptureViewController defines the delegate protocol and has a method that passes back data and references to the child view controller so that CITReportCreator can interact with it's data, close the related XIB, etc.
I believe I'm getting the delegate and protocol established correctly, and verified that my 'delegate' object still contains data when it is called, but I'm getting a EXC_BAD_ACCESS method when my view controller tries to pass data back to the delegate in this line of code:
[self.delegate childViewControllerDidFinish:self];
Here's a good portion of the rest of my code. I had this working by using CITRootViewController as my delegate instead of the CITReportCreator class, but now that I'm separating the code, something has broke.
CITReootViewController.m (the view controller that calls the Report Creator)
//create a nrew report
-(IBAction)createReport:(id)sender {
CITReportCreator *report = [CITReportCreator alloc];
[report createNewReport:self];
}
CITReportCreator.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "CITImageCaptureViewController.h"
#interface CITReportCreator : NSObject <CITImageCaptureDelegate>
#property (strong, nonatomic) NSArray *imageList;
#property (nonatomic) NSInteger imageIndex;
-(int) createNewReport:(UIViewController *)parent ;
//Delegate Methods
-(void) childViewControllerDidFinish:(UIViewController*)viewController;
#end
And CITReportCreator.m
#import "CITReportCreator.h"
#implementation CITReportCreator
{
UIViewController *parentController;
}
#synthesize imageList;
#synthesize imageIndex;
-(int) createNewReport:(UIViewController *)parent
{
//store a reference to the parent view controller
parentController = parent;
// init code....
//head to the first image capture view
[self startImageCapture];
return 0;
}
-(int)startImageCapture
{
//pull the image name from the array of images
NSString *imageName = [imageList objectAtIndex:imageIndex];
//prep the image capture controller
CITImageCaptureViewController *capture = [[CITImageCaptureViewController alloc] initWithNibName:#"CITImageCaptureViewController" bundle:nil];
//Assign the capture controller's delegate
capture.imageName = imageName;
capture.delegate = self;
//Display the capture controller
[parentController presentModalViewController:capture animated:YES];
return 0;
}
//a break point set here never gets hit.
-(void) childViewControllerDidFinish:(UIViewController*)viewController;
{
[viewController dismissModalViewControllerAnimated:YES];
}
#end
And finally, the CITImageCaptureViewControllers
CITImageCaptureViewController.h
#import <UIKit/UIKit.h>
#protocol CITImageCaptureDelegate <NSObject>
-(void) childViewControllerDidFinish:(UIViewController*)viewController;
#end
#interface CITImageCaptureViewController : UIViewController
{
id<CITImageCaptureDelegate> delegate;
}
#property (nonatomic,assign) id<CITImageCaptureDelegate> delegate;
#property (nonatomic, assign) NSString *imageName;
//continue button pressed method
-(IBAction)continueButtonPressed:(id)sender;
#end
And the .m file
#import "CITImageCaptureViewController.h"
#interface CITImageCaptureViewController ()
#end
#implementation CITImageCaptureViewController
#synthesize navItem;
#synthesize imageName;
#synthesize delegate = _delegate; //i think this may be part of the problem
//cutting out initWithNibName, viewDidLoad, etc...
- (IBAction)continueButtonPressed:(id)sender
{
[self.delegate childViewControllerDidFinish:self];
}
#end
I find nothing with delegates and protocols all that simple, but I'm guessing I'm missing a small change somewhere. Can you help me head in the right direction?

Custom Delegate, dismiss popover from another view

I could use some help with custom delegates. I'm trying to make a protocol that sends a message to its delegate to dismiss the popover view. Here is what I'm trying.
In the popoverViewController.h
#import <UIKit/UIKit.h>
#protocol MyPopoverDelegate <NSObject>
-(void) didSelectLanguage;
#end
#interface Popover : UITableViewController{
id <MyPopoverDelegate> delegate;
NSMutableArray *languageData;
}
#property (nonatomic, assign) id <MyPopoverDelegate> delegate;
#end
.m
#synthesize delegate;
...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"You selected %#", [languageData objectAtIndex:[indexPath row]]);
[self.delegate didSelectLanguage];
}
...
And in the ViewController that presents the popover
#import <UIKit/UIKit.h>
#import "popoverViewController.h"
#interface ChoicesChoices : UIViewController <UIPopoverControllerDelegate, MyPopoverDelegate>{
UIPopoverController *popover;
}
- (IBAction)facebook:(id)sender;
- (IBAction)twitter:(id)sender;
- (IBAction)sms:(id)sender;
- (IBAction)copy:(id)sender;
- (IBAction)email:(id)sender;
- (IBAction)home:(id)sender;
- (IBAction)mute:(id)sender;
- (IBAction)note:(id)sender;
#property (nonatomic, retain) UIPopoverController* popover;
#end
and .m
#synthesize popover;
...
- (void)didSelectLanguage{
[popover dismissPopoverAnimated:YES];
NSLog(#"didSelectLanguage fired");
}
When I select a row in the table of the popover, didSelectLanguage does not get called. Any ideas on what I might be doing wrong? Thanks for your help.
Make sure you are setting your delegate to the be the view controller that is presenting your popover. Something like this in ChoicesChoices.m:
- (void)presentPopover
{
// assuming ARC for all allocations
Popover *myController = [Popover new];
myController.delegate = self;
self.popover = [[UIPopoverController alloc] initWithContentViewController:myController];
[self.popover presentPopover...]; // two flavors here, FromRect: and FromBarButtonItem:, that's left up to you to choose which one is correct.
}
Make sure you set the delegate in the presenting view controller when you create the instance of your custom class.
popover.delegate = self
Also, it looks like your property is a standard popover controller instead of an instance of your custom view controller.

XCode: Call action in main view from modal view

I am trying to call an action (changeMainNumber) in a main view controller from a modal view controller. The action should change the UILabel mainNumber to 2. In ViewController.h, I have:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController {
IBOutlet UILabel *mainNumber;
}
#property (nonatomic, retain) UILabel *mainNumber;
-(IBAction)changeMainNumber;
ViewController.m:
#import "ViewController.h"
#implementation ViewController
#synthesize mainNumber;
- (IBAction)changeMainNumber:(id)sender {
mainNumber.text = #"2";
}
The next view controller is the modal view controller.
ModalViewController.h:
#import <UIKit/UIKit.h>
#class ViewController;
#interface ModalViewController : UIViewController {
}
-(IBAction)callChangeMainNumber:(id)sender;
and ModalViewController.m:
#import "ModalViewController.h"
#implementation ModalViewController
- (IBAction)callChangeMainNumber {
ViewController *viewController = [[ViewController alloc] init];
[viewController changeMainNumber];
}
With this setup the app keeps crashing when callChangeMainNumber is called and I can't figure out what is wrong. Any help you can provide is appreciated!
The code you posted from your ModalViewController is not referencing your ViewController. You are creating a new one in your code. The best solution to your problem would be to make your ViewController a delegate to the ModalViewController.
So in your ModalViewController.h file you should have this code above your #implementation.
#protocol ModalViewControllerDelegate
- (void)shouldChangeMainNumber;
#end
Then in your #implementation of the header have:
#property (nonatomic,assign)IBOutlet id <ModalViewControllerDelegate> delegate;
Now in the .m file where you have your IBAction method, tell the delegate that you want it to change the main number.
- (IBAction)callChangeMainNumber {
[self.delegate shouldChangeMainNumber];
}
Then in your ViewController.m file you need to set yourself as the delegate of the ModalViewController, usually in viewDidLoad is a good place to put it. So create a property in your header for the ModalViewController first and synthesize it, then add this to viewDidLoad.
self.modalViewController.delegate = self;
and finally you need to implement the delegate method in your .m file somewhere
- (void)shouldChangeMainNumber {
mainNumber.text = #"2";
}

Passing Parameter From a View Back To another View's UITableView's Cell

i have got two view.
First: FirstViewController
Second: SecondViewController
FirstViewController is my UINavigationController's root controller and inside FirstViewController I ve got UITableView. When a cell is clicked in UITableView, the view is navigated to SecondViewController. Inside SecondViewController i have UILabel. I want to assign this UILabel's value to the cell which is clicked at FirstViewController when Back button is clicked in Navigation Bar. What am i supposed to do to implement this?
I can pass value to SecondViewController from FirstViewController by creating:
SecondViewController *sv;
sv.somestring = someanotherstring;
but can not implement this at SecondViewController to pass the value to a NSString in FirstViewController.
Can u help me please?
Thank you.
ae
The typical way to handle this in the iPhone SDK is to define a delegate protocol. For instance:
#protocol SecondViewControllerDelegate
- (void) viewControllerWillDisappearWithLabelText: (NSString*)text;
#end
Then you would add a delegate property to your SecondViewController, like:
//in the .h file
#interface SecondViewController : UIViewController {
//declare instance variables
}
#property(nonatomic, assign) id<SecondViewControllerDelegate> delegate;
#end
//in the .m file
#implementation SecondViewController
#synthesize delegate;
//[code...]
#end
Then you would update FirstViewController to implement the delegate protocol:
//in the .h file
#interface FirstViewController : UIViewController<SecondViewControllerDelegate> {
//[instance variables]
}
//[methods and properties]
#end
//in the .m file
#implementation FirstViewController
//[code...]
- (void) viewControllerWillDisappearWithLabelText: (NSString*)text {
//do whatever you need to do with the text
}
//[code...]
#end
...and to set the delegate field when FirstViewController creates the SecondViewController:
SecondViewController* sv = [[SecondViewController alloc] init];
sv.somestring = someanotherstring;
sv.delegate = self;
Finally, in SecondViewController you implement viewWillDisappear to be roughly like:
- (void) viewWillDisappear: (bool)animated {
[super viewWillDisappear:animated];
if (self.delegate) {
[self.delegate viewControllerWillDisappearWithLabelText: myLabel.text];
}
}
Ya , there is much a easy way to handle this.....
You can take a Global Variable
In your Delegate.h file declare your variable:
#interface Smoke_ApplicationAppDelegate : NSObject {
UIWindow *window;
UINavigationController *navigationController;
NSString *messageString; //This would be your String Variable
}
#property(nonatomic,retain)NSString *messageString;
Secondly in Delegate.m file
#implementation Smoke_ApplicationAppDelegate
#synthesize window;
#synthesize navigationController;
#synthesize messageString; // Synthesize it over here..
This is Done .Now you can use this String Variable in All/any class you want..
To use this Global Variable.
Just import you Delegate file make the obj of it....
import "DelegateFile.h"
#implementation About
DelegateFile *appDel;
Now in Your class.m
-(void)viewDidLoad { [super viewDidLoad];
appDel=[[UIApplication sharedApplication]delegate];
}
Now you can access it anywhere in your class by this Object:
appDel.messageString
Just follow my Steps Carefully , I am sure this is definitely going to help you.....
Have a easy life,
Declare a string (stringVal)in the appdeleage and set its propert as nonatomic and retain, synthesize it also.In the second view controller you can set the label value to the appdelegate string([appdelegate setStringVal:label.text];) .You can get this value in the first view controller and use it in table(NSString *localString=appdelegate.stringVal];).
All the best.