ios - 如何使用协议(protocol)在两个 View Controller 之间传递值

标签 ios iphone delegates ios7 protocols

我有两个 ViewController:A 和 B,

我正在A中计算B的变量,然后通过创建ViewController B的对象来推送B及其变量值。B的变量在其自身中声明。现在我正在更改 ViewController B 中变量的值并返回到 A。我想使用 A 中变量的更改值。我已经尝试过此协议(protocol),但在 A 中我得到该变量的 0 值。 这是我的代码:

ViewController啊

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

实现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);}

最佳答案

我不知道为什么它不起作用,但我只是执行以下操作,它对我来说效果很好

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

合成属性名Delegate

@synthesize Delegate;

在推送期间我设置了委托(delegate)

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

在 IBAction 中

- (IBAction)chngAction:(id)sender 
{
    if([[self Delegate] respondsToSelector:@selector(chngvalue:)])
      [[self Delegate] chngvalue:chcek];
}

关于ios - 如何使用协议(protocol)在两个 View Controller 之间传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20422395/

相关文章:

ios - 我可以在两个不同的苹果开发者账户上添加一台 iOS 设备吗?

c# - 使用 lambda 表达式而不是委托(delegate)是个好主意吗?

c# - 什么时候显式使用 delegate 关键字而不是 lambda 是更好的做法?

ios - 交互关闭键盘时 UITableView contentInset 不更新

ios - 从 mvxSlidingpanels 的左侧 Pane 导航到查看模型

iphone - 在导航 Controller 上显示工具栏按钮

iPhone应用程序使用.NET开发环境?

ios - 商店套件交易错误 : "Cannot connect to iTunes Store" on ios 7 device

swift - 正确处理 session 委托(delegate)

ios - 如何更新 iOS 中覆盖 supportedInterfaceOrientations 函数的旧 Swift 代码?