I am trying to send a simple string from One viewcontroller to another viewcontroller using delegate but my delegate is not working. I am using storyboard and dont want to use segue to pass data. Here is my simple code
ViewControllerA.h
#import <UIKit/UIKit.h>
#class ViewControllerA;
#protocol viewControllerADelegate <NSObject>
-(void) addItem: (ViewControllerA *)controller data:(NSString *)item;
#end
#interface ViewControllerA : UIViewController{
__weak id <viewControllerADelegate> delegate;
}
- (IBAction)buttonPressed:(id)sender;
#property (weak) id<viewControllerADelegate> delegate;
#end
ViewControllerA.m
#import "ViewControllerA.h"
#interface ViewControllerA ()
#end
#implementation ViewControllerA
#synthesize delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)buttonPressed:(id)sender {
[self.delegate addItem:self data:#"this is data"];
}
#end
ViewControllerB.h
#import <UIKit/UIKit.h>
#import "ViewControllerA.h"
#interface ViewControllerB : UIViewController<viewControllerADelegate>
#end
ViewControllerB.m
#import "ViewControllerB.h"
#import "ViewControllerA.h"
#interface ViewControllerB ()
#end
#implementation ViewControllerB
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
ViewControllerA *vca = [storyboard instantiateViewControllerWithIdentifier:#"A"];
[vca setDelegate:self];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void) addItem: (ViewControllerA *)controller data:(NSString *)item{
NSLog(#"delegate function called");
}
#end
Am I missing something silly ? The delegate method -(void) addItem: (ViewControllerA *)controller data:(NSString *)item is not triggered.
The flaw in your design is to try sending data with delegates to an object you create yourself. You certainly don't need delegates for that as you can do it with simple properties. myViewControllerBObject.dataProperty = #"some data"]; is simply enough. What delegation is usually used for is send data back to the controller that created the current object or to any other controller somewhere in your app.
For example, move the delegate code in ViewControllerA to ViewControllerB and add a UIButton and an IBAction to ViewControllerB that will send the data back to ViewControllerA. Here it goes:
ViewControllerB.h
#import <UIKit/UIKit.h>
#class ViewControllerB;
#protocol viewControllerBDelegate <NSObject>
-(void) sendDataBack: (ViewControllerB *)controller data:(NSString *)item;
#end
#interface ViewControllerB : UIViewController
{
__unsafe_unretained id <viewControllerBDelegate> delegate;
}
#property (nonatomic, assign) id<viewControllerBDelegate> delegate;
- (IBAction)buttonTouch:(id)sender;
#end
ViewControllerB.m
#import "ViewControllerB.h"
#interface ViewControllerB ()
#end
#implementation ViewControllerB
#synthesize delegate;
....
- (IBAction)buttonTouch:(id)sender {
[self.delegate sendDataBack:self data:#"my data"];
}
#end
And in ViewControllerA, you first need to get a hold of that pushed ViewControllerB object via segues. Then implement the delegate method.
ViewControllerA.h
#import <UIKit/UIKit.h>
#import "ViewControllerB.h"
#interface ViewControllerA : UIViewController <viewControllerBDelegate>
- (IBAction)buttonPressed:(id)sender;
#end
ViewControllerA.m
#import "ViewControllerA.h"
#interface ViewControllerA ()
#end
#implementation ViewControllerA
......
- (IBAction)buttonPressed:(id)sender {
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
NSLog(#"id %#", [segue destinationViewController]);
ViewControllerB *vcb = (ViewControllerB *)[segue destinationViewController];
vcb.delegate = self; //key point
}
- (void)sendDataBack:(ViewControllerB *)controller data:(NSString *)item
{
NSLog(#"Here is the data %# and the controller it comes from %#", item, controller);
}
#end
Hope this will help you get a better understanding of communication with delegates.
Make the delegate variable (strong, nonatomic) instead of (__weak).
Related
I do not understand because the error appears "Method in protocol not implemented"
myProtocol.h
#import <Foundation/Foundation.h>
#protocol myProtocol <NSObject>
-(UIImage *)transferImage;
#end
ViewController.h
#import "SecondClass.h"
#interface ViewController : UIViewController<myProtocol, UINavigationControllerDelegate>
{
UIView *view;
}
#property (nonatomic,retain) UIImageView *imageView;
- (IBAction)sendImage:(id)sender;
#end
ViewController.m
#import "ViewController.h"
#import "SecondViewController.h"
#import "myProtocol.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"VoodooVibe#2x.png"]];
[view addSubview:_imageView];
NSLog(#"I am in VC.m");
}
-(UIImage *)transferImage{
NSLog(#"I am in transferImage");
return _imageView.image;}
- (IBAction)sendImage:(id)sender {
SecondViewController *secClass = [[SecondViewController alloc]init];
secClass.delegate=self;[secClass callTransfer];NSLog(#"I am in sender");[self.navigationController pushViewController:secClass animated:YES];}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
SecondViewController.h
#import <UIKit/UIKit.h>
#import "myProtocol.h"
#import "ViewController.h"
#interface SecondViewController : UIViewController<myProtocol,UINavigationControllerDelegate> {
UIView *secondView;
IBOutlet UIImageView *myImage;
id <myProtocol> myDelegate;
}
#property (nonatomic,strong) UIImageView *myImage;
#property(nonatomic,weak) id delegate;
-(void)callTransfer;
#end
SecondViewController.m
#import "SecondViewController.h"
#import "ViewController.h"
#import "myProtocol.h"
#interface SecondViewController ()
#end
#implementation SecondViewController
#synthesize delegate,myImage;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[secondView addSubview:myImage];
}
-(void)callTransfer
{
myImage.image=[delegate performSelector:#selector(transferImage)];
myImage.image=[UIImage imageNamed:#"VoodooVibe#2x.png"];
NSLog(#"%#",myImage.image);
NSLog(#"I am in call transfer");
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
You call the delegate method inside the SecondViewController but you didn't insert it. If you get a warning like ... not implemented it just says, you forgot to include a method.
You could insert the method like this
-(UIImage *)transferImage{
//do something here if delegate has been called
}
or you just add a parameter above the method inside your delegate block:
#optional
if you don't specify it, all methods will be set to #required initial.
it is as simple as you have declared a method in your protocol implementation but have not implemented the same. In your Second VC you have not implemented the method "tranfer image" . So the compiler is generating a warning
I started testing ECSlidingViewController and after I tried to access FirstTopViewController I have a big trouble - because in FirstToViewController I already have ZBarReaderDelegate implemented and all examples of delegate are not triggering any method from my delegate.
Basically I have this stuff:
FirstTopViewController.h
#import ...MyStuff...
#import "UnderRightViewController.h"
#interface FirstTopViewController : UIViewController <RightViewDelegate, ZBarReaderDelegate>
#property (weak, nonatomic) IBOutlet UITextView *labelTotal;
#end
FirstTopViewController.m
#import "FirstTopViewController.h"
#implementation FirstTopViewController
- (void)setTotalViewController:(UnderRightViewController*)controller didTotalChange:(NSString*)total
{
//labelTotal.text = total;
NSLog(#"I'm here!!! and received %#", total);
}
From other side I have
UnderRightViewController.h
#import <UIKit/UIKit.h>
#import "ECSlidingViewController.h"
#class UnderRightViewController;
#protocol RightViewDelegate <NSObject>
- (void)setTotalViewController:(UnderRightViewController*)controller didTotalChange:(NSString*)total;
#end
#interface UnderRightViewController : UITableViewController
#property (nonatomic, weak) id <RightViewDelegate> delegate;
#end
UnderRightViewController.m
#import "UnderRightViewController.h"
#interface UnderRightViewController ()
#end
#implementation UnderRightViewController
#synthesize delegate;
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[delegate setTotalViewController:self didTotalChange:#"foo"];
}
#end
I'm trying this entire day solve this puzzle but I never get setTotalViewController fired.
Thanks in advance.
Friend you did a small mistake, when you navigate from FirstTopViewController to UnderRightViewController at that time you need to do this in FirstTopViewController.m:-
UnderRightViewController *obj = [[UnderRightViewController
alloc] initWithNibName:#"UnderRightViewController" bundle:nil];
obj.delegate = self; // u forget to assign protocol handler
[self.navigationController pushViewController:obj animated:YES];
[obj release];
You don't have any code that is setting the delegate for the UnderRightViewController. I don't know what object owns both of these controllers, but before either UnderRightViewController and FirstTopViewController are displayed it should run code something like this:
FirstTopViewController *ftvc = //... where ever you get a reference to this from
UnderRightViewController *urvc = ...;
urvc.delegate = ftvc;
In your above code you are using custom delegates and also you have used it for sending message to onecontroller class to another controller class. So below is the same sample code of custom delegates, it is working fine in similar way you have to implement and also the problem in your code is you are not setting the delegate, so please follow below how to set the same and call the method. here i have used your same method only return type i have defined as NSString in-spite of void for explaining purpose, but you can use void according to your requirement hope it will be helpful to you:-
First Controller Class AWindowController.h
#interface AWindowController : NSWindowController<sampleDelegate>
{
NSString *textA;
}
#property(readwrite,retain)NSString *textA;
-(IBAction)doSet:(id)sender;
#end
#import "AWindowController.h"
#import "BWindowController.h"
#interface AWindowController ()
#end
#implementation AWindowController
#synthesize textA;
- (id)initWithWindow:(NSWindow *)window
{
self = [super initWithWindow:window];
if (self) {
// Initialization code here.
}
return self;
}
- (NSString *)setTotalViewController:(BWindowController*)controller didTotalChange:(NSString*)total
{
NSLog(#"recieved");
return #"recieved";
}
- (void)windowDidLoad
{
[super windowDidLoad];
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
-(NSString*)windowNibName
{
return #"AWindowController";
}
-(IBAction)doSet:(id)sender
{
[self setTextA:#"Awindow Button Pressed"];
BWindowController *b=[[BWindowController alloc]init];
b.delegate=self;
[b showWindow:self];
}
#end
Second Controller Class BWindowController.h
#import <Cocoa/Cocoa.h>
#import "sampleDelegate.h"
#class BWindowController;
#protocol sampleDelegate <NSObject>
#required
//-(NSString *)getDataValue;
- (NSString *)setTotalViewController:(BWindowController*)controller didTotalChange:(NSString*)total;
#end
#interface BWindowController : NSWindowController<sampleDelegate>
{
NSString *bTextValue;
id<sampleDelegate>delegate;
}
#property(readwrite,retain)NSString *bTextValue;
#property(readwrite,assign)id<sampleDelegate>delegate;
#end
#import "BWindowController.h"
#interface BWindowController ()
#end
#implementation BWindowController
#synthesize bTextValue,delegate;
- (id)initWithWindow:(NSWindow *)window
{
self = [super initWithWindow:window];
if (self) {
// Initialization code here.
}
return self;
}
- (NSString *)setTotalViewController:(BWindowController*)controller didTotalChange:(NSString*)total;
{
return nil;
}
- (void)windowDidLoad
{
NSString *str= [[self delegate]setTotalViewController:self didTotalChange:#"recieved"];
self.bTextValue=str;
[super windowDidLoad];
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
-(NSString*)windowNibName
{
return #"BWindowController";
}
#end
Attached screen shot in Output:-
Below is window is the AwindowController.h class
Below in the same above window pressing the button and when Awindow button pressed data will send
and notification will be recieved in Bwindow using above define custom delegates as attached in the screen shot.
I'm working on an iPad App and i'm having issue with delegate... the protocol method does not get invoked. i'm not sure what i'm missing, here is my code.
#protocol pickerLabelProtocol <NSObject>
- (void)selectedPickerData:(UILabel *)sender;
#end
#interface showPickerVC : UIViewController
#property (nonatomic, strong) id <pickerLabelProtocol> delegate;
#end
#implementation showPickerVC
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
//i used breakpoint, the 'delegate' is always nil for some reason?
[self.delegate selectedPickerData:self.mainLabel];
}
----------------------
#interface someViewController : UIViewController <pickerLabelProtocol>
#property (nonatomic, strong) showPickerVC *showPicker;
#end
#implementation someViewController
- (void)selectedPickerData:(UILabel *)sender
{
//protocol method
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.showPicker = [[showPickerVC alloc]init];
self.showPicker.delegate = self;
}
I can not got any mistake From your code but i suggest you that Be clear about when you create object of showPickerVC add it's delegate self
Such Like ,
showPickerVC *obj = [[showPickerVC alloc] init];
obj.delegate = self; /// YOur protocol delegate
.
.
[self presentModalViewController:obj animated:YES];
And Also add code as following
#implementation showPickerVC
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
if([self.delegate respondsToSelector:#selector(selectedPickerData:)])
{
[self.delegate selectedPickerData:self.mainLabel];
}
}
For More information about How to create/use of Protocol.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Passing model objects from one view controller to another in a navigation stack
I am trying to pass the control between two views in iphone. I have tried this and it works fine when you pass from the first view controller to the second but when i click the second, it blanks out. Why is that so? Any help is appreciated.. Thanks...
Viewcontroller.h
#import <UIKit/UIKit.h>
#import "ViewController2nd.h"
#interface ViewController : UIViewController <SecondViewControllerDelegate>
{
IBOutlet UILabel *lbl;
}
-(IBAction)passdata:(id)sender;
#end
Viewcontroller.m
#import "ViewController.h"
#import "ViewController2nd.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void) changeLabel:(NSString*)str{
lbl.text = #"Hello";
}
-(IBAction)passdata:(id)sender{
ViewController2nd *second = [[ViewController2nd alloc] initWithNibName:nil bundle:nil];
[self presentViewController:second animated:YES completion:^{ }];
}
#end
ViewController2nd.h
#import <UIKit/UIKit.h>
#protocol SecondViewControllerDelegate <NSObject>
#optional
-(void) changeLabel:(NSString*)str;
#end
#interface ViewController2nd : UIViewController{
IBOutlet UIButton *bttn;
}
-(IBAction)bttnclicked;
-(IBAction)back:(id)sender;
#end
ViewController2nd.m
#import "ViewController2nd.h"
#import "ViewController.h"
#interface ViewController2nd ()
#end
#implementation ViewController2nd
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)bttnclicked{
}
-(IBAction)back:(id)sender{
ViewController *first = [[ViewController alloc] initWithNibName:nil bundle:nil];
[self presentmodalViewController:first animated:YES completion:^{ }];
}
#end
Am i missing something?
If your requirement is to go to the first view change the back: method like:
-(IBAction)back:(id)sender
{
[self dismissViewControllerAnimated:YES completion:NULL];
}
Don't display the parentView as the childView of the chilkdViewController. It also makes memory issues and logical issues.
So if you want to go from the childView to parentView, dismiss the childView and never create the parent object and present it there.
I want to pass data from second tab to first tab using delegates.But delegate method not triggered.here is the code (I m using storyboard)
in SecondViewController.h
#import <UIKit/UIKit.h>
#class SecondViewController;
#protocol SecondViewControllerDelegate <NSObject>
-(void) sliderValueDidChanged: (SecondViewController *)controller data:(float) sliderValue;
#end
#interface SecondViewController : UIViewController{
__weak id<SecondViewControllerDelegate> delegate;
}
- (IBAction)sliderPressed:(id)sender;
#property (weak, nonatomic) IBOutlet UISlider *mySlider;
#property(weak,nonatomic) id<SecondViewControllerDelegate> delegate;
#end
in SecondViewController.m
#import "SecondViewController.h"
#interface SecondViewController ()
#end
#implementation SecondViewController
#synthesize mySlider;
#synthesize delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewDidUnload
{
[self setMySlider:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)sliderPressed:(id)sender {
float value = mySlider.value;
[self.delegate sliderValueDidChanged:self data:value];
NSLog(#"%#",self.delegate);
}
#end
FirstViewController.h
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
#interface FirstViewController : UIViewController<SecondViewControllerDelegate>
#property (weak, nonatomic) IBOutlet UILabel *myLabel;
#end
in FirstViewController.h
#import "FirstViewController.h"
#interface FirstViewController ()
#end
#implementation FirstViewController
#synthesize myLabel;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
SecondViewController *svc = [[SecondViewController alloc]init];
svc.delegate = self;
}
- (void)viewDidUnload
{
[self setMyLabel:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void) sliderValueDidChanged: (SecondViewController *)controller data:(float) sliderValue{
myLabel.text = [[NSString alloc]initWithFormat:#"%f",sliderValue];
NSLog(#"delegate called");
}
#end
I am trying to set a slider in second tab and send the sider value to first tab which has a label. self.delegate printing null and delegate method never called.
Simply enough, as you already have the delegation code, only change the line where you create a SecondViewController object. Rather than creating a new one, you should have a reference to the one that the tab bar will show.
In the viewDidLoad of FirstViewController,
Change
SecondViewController *svc = [[SecondViewController alloc]init];
to
//assuming you have 2 view controllers in the tab bar controller, first being FirstViewController
SecondViewController *svc = [self.tabBarController.viewControllers objectAtIndex:1];
and that should do it
How do you actually get to the second tab? You're creating an instance of it in viewDidLoad, but if you switch tabs, that instance won't be used to show on screen. The system will create another instance which it'll use. You can access this by accessing the tab bar controller's viewcontrollers property and checking for SecondViewController.
EDIT: You could also question your design. I don't know much about your app, but chances are your first tab shouldn't really be the delegate for your second tab. If you want to pass along data, consider using NSNotificationCenter or persistent storage.