【问题标题】:How to use Protocol to passvalue between two viewcontrollers如何使用协议在两个视图控制器之间传递值
【发布时间】:2013-12-06 11:10:18
【问题描述】:

我有两个 ViewController:A 和 B,

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

ViewController A.h

#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);}

【问题讨论】:

  • 在某些时候,在创建对象 B 之后,您必须设置 B.delegate = A。您到底在哪里做的?
  • 显示你的 ViewController B 初始化部分

标签: ios iphone delegates ios7 protocols


【解决方案1】:

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

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

综合属性名Delegate

@synthesize 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];
}

【讨论】:

  • @vivek 把上面的东西改一下就行了,其他你做的没问题的再检查一次。希望它也对你有用。 :)
  • 其实我不知道在哪里写 [ViewControllerBObj setDelegate:self];现在它的工作thanx ...我已经在一个功能中尝试过它并且完美!现在我会在其他人身上尝试一下。
猜你喜欢
  • 2015-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多