Question

I have two ViewControllers: A and B,

I am computing variable of B in A and then pushing B with its variable value by creating object of ViewController B. Variable of B is declare in itself. Now I am changing value of variable in ViewController B and return back to the A. I want to use Changed value of variable in A. I have tried protocol for this but in A I am getting 0 value of that variable. Here is my code:

ViewController A.h

#import <UIKit/UIKit.h>
#import "B.h"
@class B;
@interface ViewController : UIViewController<nxtDelegate>
{
int vcheck;
 }
@property(nonatomic,assign) int vcheck;

Implementation of A:

#import "ViewController.h"

@interface ViewController ()

 @end

@implementation ViewController
@synthesize lbl,txt,vcheck;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
}
return self;
}

-(void)viewWillAppear:(BOOL)animated{
NSLog(@"vcheckis:%d",vcheck);

}
-(void)chngvalue:(int)i{
vcheck=i;
}

ViewController B.h

#import <UIKit/UIKit.h>

@protocol nxtDelegate <NSObject>

-(void)chngvalue:(int )i;

@end
@interface nextviewController :   UIViewController<UITableViewDelegate,UIPickerViewDelegate,UIPickerViewDataSource>
{
int chcek;
}
@property(weak,nonatomic)id<nxtDelegate> delegate;
- (IBAction)btnclick:(id)sender;
@property(nonatomic,assign) int chcek;

ViewController B.m

- (IBAction)chngAction:(id)sender {
[_delegate chngvalue:chcek];
NSLog(@"%@",_delegate);}
Was it helpful?

Solution

I don't know why it's not working but I just do the below and it's work fine for me

@property(nonatomic, assign)id<nxtDelegate> Delegate;

synthesize the property name Delegate

@synthesize Delegate;

and during push I set the delegate

ViewControllerB *ViewControllerBObj=[[ViewControllerB alloc] init];
[ViewControllerBObj setDelegate:self];
[[self navigationController] pushViewController:ViewControllerBObj animated:YES];

In IBAction

- (IBAction)chngAction:(id)sender 
{
    if([[self Delegate] respondsToSelector:@selector(chngvalue:)])
      [[self Delegate] chngvalue:chcek];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top